开发者

implementing a cast operator in a generic abstract class

I'm trying to be lazy and implement the cast operators in the abstract base class rather than in each of the derived concrete classes. I've managed to cast one way, but I'm unable to cast the other. I think it might not be possible, but wanted to pick the collective SO mind before giving up:

public interface IValueType<T>
{
    T Value{ get; set; }
}

public abstract class开发者_如何学编程 ValueType<T> : IValueType<T> {
    public abstract T Value { get; set; }
    public static explicit operator T(ValueType<T> vt) {
        if(vt == null)
            return default(T);
        return vt.Value;
    }

    public static implicit operator ValueType<T>(T val) {
        ValueType<T> vt = new ValueType<T>(); //<--- obviously this won't work as its abstract
        vt.Value = val;
        return vt;
    }
}


You need to introduce another generic parameter to identify the concrete type.

something like..

public interface IValueType<T> 
{    
    T Value{ get; set; } 
} 

public abstract class ValueType<T,K> : 
    IValueType<T> where K : ValueType<T,K>,new()
{     
    public abstract T Value { get; set; }     
    public static explicit operator T(ValueType<T,K> vt) 
    {         
        if(vt == null)            
            return default(T);         
        return vt.Value;     
    }      

    public static implicit operator ValueType<T,K>(T val) 
    {         
        K k = new K();
        k.Value = val;
        return k;    
    } 
} 

Create your concrete class

public class Test : ValueType<int,Test>
{
    public override int Value {get;set;}
}

Then

var t = new Test();
t.Value = 99;
int i = (int)t;
Test t2 = (Test)6;

Console.WriteLine(i);
Console.WriteLine(t2);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜