没有来自“ T”的装箱转换或类型参数转换

时间:2018-10-15 10:41:20

标签: c# generics

当我试图创建一个泛型类的实例时,我必须将我的泛型类型声明为一个接口,这是一个问题。 这是代码示例:

public interface ITypeInterface
{
}

public class DataWorker<T> where T : ITypeInterface
{
    private string _someData;
    public DataWorker(string someData){
        _someData = someData;
    }
    ...
}

public class AnotherClass : MustBeInterface
{

    void MustBeInterface.CreateData<T>(string data)
    {
        // Here I should call DataWorker which has type ITypeInterface
        // but compiler gives me an error:
        // there is no boxing conversion or type parameter conversion from 'T' to 'ITypeInterface'
        var dataWorker = new DataWorker<T>(data);
    }
}

public interface MustBeInterface{
    void CreateData<T>(string data);
}

因此,在类AnotherClass中,我必须实现MustBeInterface,它是库的一部分,并且无法更改。当我尝试在AnotherClass.CreateData中创建DataWorker的实例时,收到错误消息:没有从“ T”到“ ITypeInterface”的装箱转换或类型参数转换。 有什么解决方案可以实现我的目标?

1 个答案:

答案 0 :(得分:0)

您可能可以这样做:

void MustBeInterface.CreateData<T>(string data)
{
    // Here I should call DataWorker which has type ITypeInterface
    // but compiler gives me an error:
    // there is no boxing conversion or type parameter conversion from 'T' to 'ITypeInterface'
    if (typeof(T) == typeof(ITypeInterface))
        var dataWorker = new DataWorker<ITypeInterface>(data);
    else throw new IllegalOperationException(...);
}