截至铸造 - C# [英] Up casting - c#

查看:105
本文介绍了截至铸造 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class a{
  public string x1 {get;set;}
  public string x2 {get;set;}
  public string x3 {get;set;}
}

public class b:a{
}

显然变种富=(b)新一(); 将在运行时抛出一个铸造误差

Obviously var foo = (b)new a(); will throw a casting error at runtime.

唯一的其他方法可以让我觉得指派已经实例化和填充 A 结束手动复制每一个到一个新的实例<$ C的所有属性$ C> B 。

The only other way I can think to assign all the properties of an already instantiated and populated a is to manually copy each one over into a fresh instance of b.

这是正确的?

推荐答案

这类型的投是错误的,因为你不能施放父母给子女。
A型不知道键入的b 元信息。因此,你需要提供明确的类型转换操作符做这种事情,但是在这种情况下,你必须删除继承
另一种选择是定义一些接口,诸如在其它问题。

This type of cast is wrong, because you can't cast parents to their children.
Type of a doesn't know about metainformation of type b. So you need provide the explicit cast operator to do such things, but in this case you must remove inheritance.
Other option is to define some interface, such as in other questions.

更多信息:
http://msdn.microsoft.com/en-us/library/ms173105.aspx
http://msdn.microsoft.com/en-us/library/85w54y0a.aspx

More information:
http://msdn.microsoft.com/en-us/library/ms173105.aspx
http://msdn.microsoft.com/en-us/library/85w54y0a.aspx

这篇关于截至铸造 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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