将C#4允许“动态铸造”?如果没有,应该C#支持吗? [英] Will C#4 allow "dynamic casting"? If not, should C# support it?

查看:108
本文介绍了将C#4允许“动态铸造”?如果没有,应该C#支持吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是指将一个较低的接口或基类转换为一个更为派生类的动态转换,我的意思是取一个我创建的接口定义,然后动态地转换到该接口一个不同的对象NOT

I don't mean dynamic casting in the sense of casting a lower interface or base class to a more derived class, I mean taking an interface definition that I've created, and then dynamically casting to that interface a different object NOT derived from that interface but supporting all the calls.

例如,

interface IMyInterface
{
   bool Visible
   {
      get;
   }
}

TextBox myTextBox = new TextBox();
IMyInterface i = (dynamic<IMyInterface>)myTextBox;

这可以在编译时为已知类型实现,而运行时可以用动态语句声明。接口定义是已知的,因为类型是(在这个例子中),所以编译器可以确定对象是否支持由接口定义的调用,并为我们执行一个魔术来进行转换。

This could be achieved at compile time for known types, and runtime for instances declared with dynamic. The interface definition is known, as is the type (in this example) so the compiler can determine if the object supports the calls defined by the interface and perform some magic for us to have the cast.

我的猜测是,这是不支持在C#4(我找不到它的参考),但我想知道肯定。如果不是,我想讨论是否应该包括在语言的未来变体中,以及原因和反对。对我来说,在代码中启用更大的多态性似乎是一个很好的补充,而不必创建整个新类型来包装现有框架类型。

My guess is that this is not supported in C#4 (I was unable to find a reference to it), but I'd like to know for sure. And if it isn't, I'd like to discuss if it should be included in a future variant of the language or not, and the reasons for and against. To me, it seems like a nice addition to enable greater polymorphism in code without having to create whole new types to wrap existing framework types.

更新

防止有人指责我是剽窃,我不知道 Jon Skeet已经提出了这个。但是,很高兴知道我们认为极其相似的语法,这表明它可能是直观的至少。

Update
Lest someone accuse me of plagiarism, I was not aware of Jon Skeet having already proposed this. However, nice to know we thought of exceedingly similar syntax, which suggests it might be intuitive at least. Meanwhile, "have an original idea" remains on my bucket list for another day.

推荐答案

我认为Jon Skeet有这样一个提案( http ://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx ),但到目前为止,我还没有听说过C#4.0将会有。

I think Jon Skeet has had such a proposal (http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx), but so far, I haven't heard that C# 4.0 is going to have it.

这篇关于将C#4允许“动态铸造”?如果没有,应该C#支持吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆