动态对象.如何通过 TryInvoke 执行函数
本文关键字:执行 函数 TryInvoke 何通过 对象 动态 | 更新日期: 2024-11-07 06:41:53
我想通过动态对象执行静态函数,但我不知道如何在不指定类名typeof(Test1)
或typeof(Test2)
的情况下执行saveOperation。如何更好地利用这一点?
例如
class DynObj : DynamicObject
{
GetMemberBinder saveOperation;
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
saveOperation = binder;
result = this;
return true;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
Type myType = typeof(Test1 or Test2 or ....);
result = myType.GetMethod(saveOperation.Name).Invoke(null, args);
return true;
}
}
class Program
{
static void Main(string[] args)
{
dynamic d1 = new DynObj();
d1.func1(3,6);
d1.func2(3,6);
}
}
class Test1
{
public static void func1(int a, int b){...}
}
class Test2
{
public static void func2(int a, int b){ ...}
}
第二种方式用属性定义静态函数(由Carnifex提供)
class Test3
{
[DynFuncMemberAttribute]
public static void func3(int a, int b){...}
}
并获取类型
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
Type myType = null;
foreach (Type types in Assembly.GetExecutingAssembly().GetTypes())
{
foreach (MethodInfo mi in types.GetMethods())
{
foreach (CustomAttributeData cad in mi.CustomAttributes)
{
if (cad.AttributeType == typeof(DynFuncMemberAttribute))
{
myType = types;
break;
}
}
}
}
result = (myType != null)? myType.GetMethod(saveOperation.Name).Invoke(null, args): null;
return myType != null;
}
您可以使用一些属性并设置 eg。[DynFuncMemberAttribute] 到类或它自己的方法。
然后在 TryInvoke(或构造函数)中获取所有标有此属性的类型/方法,构建一些映射/缓存,瞧:)
编辑:这是使用此属性的示例。请记住,如果找到两个同名的方法,BuildCache() 将引发异常。
[AttributeUsage(AttributeTargets.Method)]
class DynFuncMemberAttribute : Attribute
{
}
class DynObj : DynamicObject
{
Dictionary<string, MethodInfo> cache;
GetMemberBinder saveOperation;
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
saveOperation = binder;
result = this;
return true;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
if (cache == null)
cache = BuildCache();
MethodInfo mi;
if (cache.TryGetValue(saveOperation.Name, out mi))
{
result = mi.Invoke(null, args);
return true;
}
result = null;
return false;
}
private Dictionary<string, MethodInfo> BuildCache()
{
return Assembly.GetEntryAssembly()
.GetTypes()
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Static))
.Where(mi => mi.GetCustomAttribute<DynFuncMemberAttribute>() != null)
.ToDictionary(mi => mi.Name);
}
}
class Program
{
static void Main(string[] args)
{
dynamic d1 = new DynObj();
d1.func1(3, 6);
d1.func2(3, 6);
}
}
class Test1
{
[DynFuncMember]
public static void func1(int a, int b)
{
Console.WriteLine("func1");
}
}
class Test2
{
[DynFuncMember]
public static void func2(int a, int b)
{
Console.WriteLine("func2");
}
}