これはおそらく一例として最もよく示されています。私はインスタンスからそれらの属性を取得したい誰かが、enum値のカスタム属性に素早くアクセスする方法を知っていますか?
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
}
が、列挙型を変換するために、厄介なようです値を文字列(名前を反映)に変換します。
もっと良い方法がありますか?
'Enum.GetName()'と比較しましたか? –