确定 DynamicObject 成员访问的预期类型

发布于 2024-11-29 20:50:24 字数 328 浏览 4 评论 0原文

是否可以确定动态成员访问需要什么类型?我已经尝试过

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

,并且在 TryGetMember 中拦截 GetMemberBinder.ReturnType 无论如何都是对象。我还实现了 TryConvert,想知道是否可以调用它来进行转换,但它从未被命中。

我是否缺少其他一些覆盖,可以让我确定调用者想要什么类型,以便我可以进行适当的转换?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

子栖 2024-12-06 20:50:24

在 C# 中,当使用动态时,编译器始终将绑定器设置为对象的返回类型,然后执行第二次动态隐式转换为预期的返回类型。因此,在从 c# 调用 DynamicObject 时,GetMemberBinder.ReturnType 将始终是对象,但这就是说,如果您返回另一种实现了 TryConvert 的跳板动态对象,您可以获得该类型,除非用户执行 var 或dynamic< /code> 作为变量,那么它们就有一个代理,在它变成静态类型之前不会执行任何操作。

ImpromptuInterface 做了一些不同的事情,但沿着这些思路,因为它也希望有一个动态实现,可以根据情况进行更改关于返回类型——只是您必须通过接口描述动态对象。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文