No Boxing Conversion for two type parameters shared Parent and Child

两盒软妹~` 提交于 2019-12-24 17:00:39

问题


I get the following error (VSC#2010 Express) on the declaration of GetChild method...

Error 1 The type 'T' cannot be used as type parameter 'T' in the generic type or method '...Child'. There is no boxing conversion or type parameter conversion from 'T' to '...IParent'.

public interface IParent<T, Id>
{
    Child<T, Id> GetChild();
}

public class Child<T, Id> where T : IParent<T, Id>
{
    public T Parent;
}

I want any class to inherit IParent, and for each such class to construct a member instance of Child.

T is the class inheriting IParent, and Id is an enum in the parent scope of that class.


回答1:


Try constraining type T in the interface as well.

public interface IParent<T, Id> where T : IParent<T, Id>
{
    Child<T, Id> GetChild();
}

public class Child<T, Id> where T : IParent<T, Id>
{
    public T Parent;

    public Child<T, Id> GetChild()
    {
        throw new NotImplementedException();
    }
}


来源:https://stackoverflow.com/questions/24543043/no-boxing-conversion-for-two-type-parameters-shared-parent-and-child

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