implementing a cast operator in a generic abstract class

前端 未结 1 1226
难免孤独
难免孤独 2021-02-13 12:56

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

1条回答
  •  野性不改
    2021-02-13 13:02

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

    something like..

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

    Create your concrete class

    public class Test : ValueType
    {
        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 讨论(0)
提交回复
热议问题