Determining the expected type of a DynamicObject member access

南笙酒味 提交于 2019-12-10 02:15:43

问题


Is it possible to determine what type a dynamic member access expects? I've tried

dynamic foo = new MyDynamicObject();
int x = foo.IntValue;
int y = (int)foo.IntValue;

And in the TryGetMember intercept GetMemberBinder.ReturnType is object either way. I also implemented TryConvert wondering if it might get invoked to do the conversion, but it never is hit.

Is there some other override I'm missing that lets me determine what Type the caller wants so that I can do the appropriate conversion?


回答1:


In C#, when using dynamic, the compiler always sets the binder to return type of object, and then does a second dynamic implicit conversion to the expected return type. So on a DynamicObject when called from c#, GetMemberBinder.ReturnType will always be object, but that said if you return another sort of springboard dynamic object with TryConvert implemented you could get that type, except if the user does var or dynamic as the variable, then they have a proxy that won't do anything until it becomes statically typed.

ImpromptuInterface does something different but along these lines, because it also has the desire to have a dynamic implementation that changes based on return types -- just you would have to describe the dynamic object via an interface.



来源:https://stackoverflow.com/questions/7044277/determining-the-expected-type-of-a-dynamicobject-member-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!