Alo*_*kin 4 c# reflection performance
var property = obj.GetType().GetProperty(blockName);
if (property == null)
{
var method = obj.GetType().GetMethod(blockName);
if (method == null)
return "[" + blockName + "]";
else
return method.Invoke(obj, null).ToString();
}
else
return property.GetValue(obj, null).ToString();
Run Code Online (Sandbox Code Playgroud)
此代码应查找名为blockName's value 的属性.如果找到该属性,则应返回其值.如果没有,它应该寻找名为blockName's value的函数.如果找到,则应调用它并返回返回的值.如果它找不到方法,它应该返回[ blockName's value].
它工作得很好,但我正在寻找提高效率的方法.我不想将方法转换为属性或属性到方法,因为将来我也会添加参数.你能帮我吗?
谢谢.
如果您知道签名(即返回类型和参数),那么Delegate.CreateDelegate可以在这里非常有效地使用:
using System;
using System.Reflection;
class Test
{
public string Foo(int i)
{
return i.ToString();
}
static void Main()
{
MethodInfo method = typeof(Test).GetMethod("Foo");
Func<Test, int, string> func = (Func<Test, int, string>)
Delegate.CreateDelegate(typeof(Func<Test, int, string>), null, method);
Test t = new Test();
string s = func(t, 123);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,对于属性,您需要查看GetGetMethod和GetSetMethod.如果您不知道签名,这不会很好,因为DynamicInvoke非常慢.
要从中获益Delegate.CreateDelegate,您必须缓存并重新使用委托实例; 不要每次都重新创建它!
对于属性,即使您不知道属性类型,也可以考虑使用HyperDescriptor(您需要添加1行以启用超级描述符):
using System.ComponentModel;
class Test
{
public int Bar { get; set; }
static void Main()
{
PropertyDescriptor prop = TypeDescriptor.GetProperties(
typeof(Test))["Bar"];
Test t = new Test();
t.Bar = 123;
object val = prop.GetValue(t);
}
}
Run Code Online (Sandbox Code Playgroud)