質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top