これは、おそらく例で最もよく示されています。私は属性を持つ列挙型を持っています:
public enum MyEnum {
[CustomInfo("This is a custom attrib")]
None = 0,
[CustomInfo("This is another attrib")]
ValueA,
[CustomInfo("This has an extra flag", AllowSomething = true)]
ValueB,
}
インスタンスからこれらの属性を取得したい:
public CustomInfoAttribute GetInfo( MyEnum enumInput ) {
Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum )
//here is the problem, GetField takes a string
// the .ToString() on enums is very slow
FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() );
//get the attribute from the field
return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ).
FirstOrDefault() //Linq method to get first or null
as CustomInfoAttribute; //use as operator to convert
}
これはリフレクションを使用しているため、多少の遅延が予想されますが、列挙値のインスタンスが既にある場合に、列挙値を文字列 (名前を反映する) に変換するのは面倒です。
誰かがより良い方法を持っていますか?