重载明确的类型转换操作符明确、类型、操作

2023-09-03 07:10:07 作者:逝去的ゝ阳光

我有这块code:

 公共类腿:ProxiestChild
{
    公共虚拟名称{;组; }
}
 

问题是:

  VAR腿=新的腿(); //腿不是腿,而是ProxiedLeg

VAR trueleg =(腿)腿; //例外腿是ProxiedLeg
 

我需要这样的事情

 公共类ProxiestChild
{
    //一些方法重载明确的CAST
    //那里接收代理对象我返回的对象非代理
    //被铸造
}
 
重载C 操作符 知识学习

解决方案

您可以使用转换操作符明确实现自定义类型转换这里详细介绍:

http://msdn.microsoft.com/en-us/library/85w54y0a(v=VS.100).aspx

千万要小心,为了便于阅读它往往被混淆地看到一种神奇强制转换为另 - 人并不总是先想到有在游戏转换操作符

I have this piece of code:

public class Leg : ProxiestChild
{
    public virtual Name { get; set; }
}

the problem is:

var leg = new Leg(); // leg is not Leg, instead ProxiedLeg

var trueleg = (Leg)leg; // exception leg is a ProxiedLeg

i need something like this

public class ProxiestChild
{
    // some method that overloads explicit CAST
    // where receiving the proxied object i returns the unproxied object
    // to be casted
}

解决方案

You can implement custom type casting using the conversion operators implicit or explicit as detailed here:

http://msdn.microsoft.com/en-us/library/85w54y0a(v=VS.100).aspx

Do be careful with this, for readability it can often be confusing to see one type magically cast to another - people don't always first think that there are conversion operators in play.