获得通用的呼叫类型来动态对象的方法
我开始在.NET中使用动态对象的工作,我无法弄清楚如何做一些事情。
I'm starting to work with dynamic objects in .Net and I can't figure out how to do something.
我有一个从DynamicObject继承的类,我重写TryInvokeMember方法。
I have a class that inherits from DynamicObject, and I override the TryInvokeMember method.
例如
class MyCustomDynamicClass : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
// I want to know here the type of the generic argument
}
}
和那个方法里面我想知道的类型(如果有的话)的调用通用的参数。
And inside that method I want to know the type (if any) of the generic arguments in the invocation.
如
。如果我调用下面的代码,我要得到我的动态对象。
e.g. If I invoke the following code, I want to get the value of System.Boolean and System.Int32 inside the overrided method of my dynamic object
dynamic myObject = new MyCustomDynamicClass();
myObject.SomeMethod<bool>("arg");
myObject.SomeOtherMethod<int>("arg");
目前,如果我把overrided方法中的断点,我可以得到的被调用的方法的名称( 的someMethod和SomeOtherMethod,也的参数值,但不是泛型类型)。
Currently if I place a breakpoint inside the overrided method I can get the name of the method being invoked ("SomeMethod" and "SomeOtherMethod", and also the values of the arguments, but not the generic types).
我怎样才能获得这些价值?
How can I get these values?
谢谢!
其实我通过粘结剂的层次看,发现一个属性用在物体的内部字段所需的值。
Actually I looked through the hierarchy of the binder and found a property with the needed values in the internal fields of the object.
的问题是,该属性不被暴露,因为它使用C#的特异性代码/类,因此,性能。必须使用反射来访问
The problem is that the property isn't exposed because it uses C#-specific code/classes, therefore the properties must be accessed using Reflection.
我发现这个博客的日本代码: HTTP: //neue.cc/category/programming (我不读任何日本人,所以我不知道如果作者确实描述了同样的问题。
I found the code in this japanese blog: http://neue.cc/category/programming (I don't read any japanese, therefore I'm not sure if the author actually describes this same issue
这里的片断:
var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder");
var typeArgs = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList<Type>);
typeArgs是包含类型的调用方法时所使用的通用的参数列表。
typeArgs is a list containing the types of the generic arguments used when invoking the method.
希望这可以帮助别人。