implementing a cast operator in a generic abstract class

亡梦爱人 提交于 2019-12-03 10:48:58

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!