在一个通用的抽象类实现转换运算符 [英] implementing a cast operator in a generic abstract class

查看:130
本文介绍了在一个通用的抽象类实现转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想偷懒,在抽象基类,而不是在每一个具体的派生类实现投运营商。我已经成功地施展的一种方式,但我无法投其他。我想可能是不可能的,但要挑集体放弃以前那么介意:

 公共接口IValueType< T> 
{
的T值{搞定;组; }
}

公共抽象类的ValueType< T> :IValueType< T> {
公共抽象的T值{搞定;组; }
公共静态明确运营商T(值类型< T> VT){
如果(VT == NULL)
返回默认值(T);
返回vt.Value;
}

公共静态隐运营商的ValueType< T>(T VAL){
值类型< T> VT =新的ValueType< T>(); //< ---显然,这不会因为它的抽象
工作vt.Value = VAL;
返回VT;
}
}


解决方案

您需要引入另一个泛型参数来确定具体类型。



喜欢的东西..

 公共接口IValueType< T> 
{
的T值{搞定;组; }
}

公共抽象类的ValueType< T,K> :
IValueType< T>其中K:值类型< T,K>新()
{
公共抽象的T值{搞定;组; }
公共静态明确运营商T(值类型< T,K> VT)
{
如果(VT == NULL)
返回默认值(T);
返回vt.Value;
}

公共静态隐运营商的ValueType< T,K>(T VAL)
{
k的序列K =新K();
k.Value = VAL;
复位K;
}
}



创建的具体类

 公共类测试:值类型< INT,试验> 
{
公众覆盖int值{获取;集;}
}

然后

  VAR T =新的测试(); 
t.Value = 99;
INT I =(INT)吨;
测试T2 =(测试)6;

Console.WriteLine(ⅰ);
Console.WriteLine(T2);


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);

这篇关于在一个通用的抽象类实现转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆