是否有一种方法可以将枚举参数正确解析为动态调用的方法



想象一下以下问题:

//Assembly 1
namespace R {
public class Remote
{
public enum SomeTypes
{
A = 12,
B = 14,
C = 16
}

public void DoSomething(SomeTypes s, int a)
{
Console.WriteLine((int)s * a);
}
}
}
//Assembly 2
namespace L
{
public class Local
{
public enum SomeTypes
{
A = 12,
B = 14,
C = 16
}

public Local()
{
assembly = ....;

dynamic instance = assembly.DefinedTypes.First(t => t.GetName() == "R.Remote").GetConstructor(Type.EmptyTypes).Invoke(new object [] {});

instance.DoSomething(SomeTypes.A,3); //this is where it crashes because of an argument mismatch, fair point: One is R.Remote.SomeTypes the other one L.Local.SomeTypes
instance.DoSomething((int)SomeTypes.A,3); //this should work technically, does not, one is R.Remote.SomeTypes the other one int, despite the fact that they can be converted into each other
instance.DoSomething((dynamic)SomeTypes.A,3); //just a hacky guess, but this does not work either
}
}
}

有人知道如何在不触发参数不匹配异常的情况下调用DoSomething(…(吗?

以防万一:我无法访问远程程序集。

提前非常感谢:(

如果由于某种原因通过反射获取类型,则可以继续使用它来获取所需的枚举值并调用方法:

var remoteType = typeof(Remote); //you remote type from assembly
// you will use var remoteType = assembly.DefinedTypes.First(t => t.GetName() == "R.Remote");
var method = remoteType.GetMethod("DoSomething"); // find needed method somehow
var instance = Activator.CreateInstance(remoteType); // creates instance via parameterless ctor
var remoteSomeType = remoteType.GetNestedType("SomeTypes"); // get Remote.SomeType
var a = remoteSomeType.GetField("A").GetValue(null); // Get Remote.SomeType.A enum value
method.Invoke(instance, new object[]{a, 3}); // call method

请注意,通常动态/反射是缓慢的,因此如果您计划频繁调用此方法,则应该考虑";高速缓存";反射,例如试图使用表达式树编译它。

最新更新