Custom Attributes and enumeration

Source: Internet
Author: User

A long time ago, I knew that. Net had reflection technology, and the database component I implemented earlier was reflection. However, I did not know that there were custom attributes before, so I did not regard reflection as an important technology. But now, I find that, with the support of custom attributes, reflection can actually complete a lot of tasks, making complicated operations easy.

The switch operation using reflection distribution I wrote in the previous section is a typical example. Without custom attributes, the program in this example will not be able to complete some special operations, in addition, there is a lot of possibility of errors hidden, and after using custom attributes, all this is under control, but the range of using it is greatly widened, this gives it more freedom to use.

Two days ago, I wrote a custom attribute about Enum:

Code

 public class ShowStringAttribute : Attribute
{
private string _ShowString;

public string ShowString
{
get { return _ShowString; }
}

public ShowStringAttribute(string ShowString)
{
_ShowString = ShowString;
}
}

Although now ,. in net, the tostring operation on Enum will output the enum name. However, in many cases, we want to display it in different languages, or, the string we want to display contains invalid characters (such as spaces, which are invalid characters for variables, but a common requirement for display, it helps us to display the string defined by Enum, but unfortunately, although any Enum is from system. enum is derived. However, we cannot rewrite its tostring function. Therefore, we need a helper class to help its output:

Code

 public class EnumStringHelper
{
public static string ToString(object o)
{
Type t = o.GetType();
string s = o.ToString();
ShowStringAttribute[] os = (ShowStringAttribute[])t.GetField(s).GetCustomAttributes(typeof(ShowStringAttribute), false);
if ( os != null && os.Length == 1 )
{
return os[0].ShowString;
}
return s;
}
}

 

Usage, like this:

Code

 Public Enum enumtest
{
[Showstring ("test")]
Test,

[Showstring ("Run")]
Run,

Exit
}

Class Program
{
[Stathread]
Static void main (string [] ARGs)
{
Console. writeline ("-------------------------------------------");
Console. writeline (enumstringhelper. tostring (enumtest. Test ));
Console. writeline (enumstringhelper. tostring (enumtest. Run ));
Console. writeline (enumstringhelper. tostring (enumtest. Exit ));
Console. writeline ("-------------------------------------------");
Console. Readline ();
}
}

Of course, the enumstringhelper. tostring is really ugly, which prompted me to start thinking about the implementation mechanism of enum. Although it still does not solve the purpose of rewriting the tostring function of Enum, but I think this is also an interesting problem.

In C ++ and Java, Enum is only an int deformation, so in fact, it is impossible to implement the so-called "strong type check", so in. net is implemented in what way? After some practice and thinking, I think, in fact, when we are in. when determining an Enum in. net, of course, first from the system. enum is inherited, And the other point is that each defined enumerated value is a static read-only instance of this class! The following code demonstrates this, and this method also allows us to implement a "strong type check" enumeration in C ++ or Java:

Code

 public abstract class EnumBase
{
private int _value;

protected EnumBase(int value)
{
_value = value;
}

public override string ToString()
{
Type t = this.GetType();
FieldInfo[] fis = t.GetFields();
foreach ( FieldInfo fi in fis )
{
EnumBase eb = (EnumBase)fi.GetValue(this);
if ( eb._value == this._value )
{
return fi.Name;
}
}
throw new NotImplementedException();
}
}

public class MyEnum : EnumBase
{
private MyEnum(int v) : base(v) {}

public static readonly MyEnum test = new MyEnum(0);
public static readonly MyEnum run = new MyEnum(1);
public static readonly MyEnum exit = new MyEnum(2);
}

Of course, I also hope that the custom attributes defined for Enum can be used for the enum I implemented myself. Since I think its implementation mechanism is the same as that of Enum, of course, the custom attribute should also be easy to use. This time, we implemented a common class, so we can rewrite its tostring function:

Code

 Public abstract class enumbase
{
Private int _ value;

Protected enumbase (INT value)
{
_ Value = value;
}

Public override string tostring ()
{
Type T = This. GetType ();
Fieldinfo [] FCM = T. getfields ();
Foreach (fieldinfo fi in FCM)
{
Enumbase EB = (enumbase) Fi. getvalue (this );
If (EB. _ value = This. _ value)
{
Return fi. Name;
}
}
Throw new notimplementedexception ();
}

}

Public abstract class namedenumbase: enumbase
{
Protected namedenumbase (int v): Base (v ){}

Public override string tostring ()
{
Type T = This. GetType ();
String S = base. tostring ();
Showstringattribute [] OS = (showstringattribute []) T. getfield (s). getcustomattributes (typeof (showstringattribute), false );
If (OS! = NULL & OS. Length = 1)
{
Return OS [0]. showstring;
}
Return S;
}
}

Public class myenum: namedenumbase
{
Private myenum (int v): Base (v ){}

[Showstring ("test")]
Public static readonly myenum test = new myenum (0 );

[Showstring ("Run")]
Public static readonly myenum run = new myenum (1 );

Public static readonly myenum exit = new myenum (2 );
}

Class Program
{
[Stathread]
Static void main (string [] ARGs)
{
Console. writeline ("-------------------------------------------");
Console. writeline (myenum. Test. tostring ());
Console. writeline (myenum. Run. tostring ());
Console. writeline (myenum. Exit. tostring ());
Console. writeline ("-------------------------------------------");
Console. Readline ();
}
}

Of course, the enum in. Net also implements the strong type check after "bit and". Although it is not very difficult, it is still a troublesome problem and I will not implement it.

 

From

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.