overloading explicit CAST operator

2019-02-23 17:22发布

问题:

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
}

回答1:

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.