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

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

问题描述

我不是指将一个较低的接口或基类转换为更多派生类的动态转换,我的意思是采用我创建的接口定义,然后动态地向该接口转换不同的对象NOT派生自该界面,但支持所有的电话。



例如,

 界面IMyInterface 
{
bool可见
{
get;
}
}

TextBox myTextBox = new TextBox();
IMyInterface i =(动态< IMyInterface>)myTextBox;

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



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



更新

有人指责我剽窃,我不知道 Jon Skeet已经提出了这个。然而,很高兴知道我们认为极其相似的语法,这表明它至少可能是直观的。同时,有一个原创的想法仍然在我的桶列表中一天。

解决方案

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


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.

For example,

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.

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.

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.

解决方案

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天全站免登陆