誰でも知ってい迫力のある姿を見せているカスタム属性の列挙型。
-
09-06-2019 - |
質問
このホームページを示す一例です。私の列挙型属性:
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値を文字列の名前がすでに持っていインスタンスです。
いてよりよい。
解決
最ます。
すると、より素早く行う静的光のILコードのダイナミック方法及びILGenerator.はんだこGetPropertyInfoることができていないかせんでしたが、少し足を延ばせば出CustomAttributeInfoしています。
例えば、コードの発ゲッターからの物件
public delegate object FastPropertyGetHandler(object target);
private static void EmitBoxIfNeeded(ILGenerator ilGenerator, System.Type type)
{
if (type.IsValueType)
{
ilGenerator.Emit(OpCodes.Box, type);
}
}
public static FastPropertyGetHandler GetPropertyGetter(PropertyInfo propInfo)
{
// generates a dynamic method to generate a FastPropertyGetHandler delegate
DynamicMethod dynamicMethod =
new DynamicMethod(
string.Empty,
typeof (object),
new Type[] { typeof (object) },
propInfo.DeclaringType.Module);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
// loads the object into the stack
ilGenerator.Emit(OpCodes.Ldarg_0);
// calls the getter
ilGenerator.EmitCall(OpCodes.Callvirt, propInfo.GetGetMethod(), null);
// creates code for handling the return value
EmitBoxIfNeeded(ilGenerator, propInfo.PropertyType);
// returns the value to the caller
ilGenerator.Emit(OpCodes.Ret);
// converts the DynamicMethod to a FastPropertyGetHandler delegate
// to get the property
FastPropertyGetHandler getter =
(FastPropertyGetHandler)
dynamicMethod.CreateDelegate(typeof(FastPropertyGetHandler));
return getter;
}
他のヒント
私は一般的に見を反映するもの迅速などのない動的に呼び出します。
まだ読みの属性の列挙型、アプローチで十分に作動するのでなく高いパフォーマンスを発揮。
やんはういう単純明快。以上こだけゲインを数msない場合があります。
所属していません StackOverflow