如何将Generic <t>转换为Generic <r>,其中T是R的子类?</r> </t>

时间:2013-08-15 20:18:43

标签: c# generics inheritance

有没有办法定义显式转换器或类似的东西,以便编译器可以从Generic<T> Generic<R>自动填充where T : R

我得到的错误信息是:

  

值“参考1[Dog]" is not of type "Reference 1 [宠物]”,不能在此通用集合中使用。

我的参考课如下:

public interface IReference<T>
{
    T Value { get; }
}

public class Reference<T> : IReference<T>
{
    #region Properties
    public string ref_type { get; set; }
    public string ref_id { get; set; }
    public Uri href { get; set; }

    private bool resolved = false;
    private T _value = default(T);

    public T Value
    { 
        get
        {
            if( !resolved && href != null ) resolve();
            else if( href == null ) return null;
            return _value;
        }
    }
    #endregion

    #region Constructors
    public Reference() { }
    public Reference(string ref_id) 
    {
        this.ref_id = ref_id;
    }
    #endregion

    #region members
    private void resolve()
    {
        if( href != null )
        {
            _value = APIRequestMethods.GetUri<T>(href);
            resolved = true;
        }
        else
            throw new Exception("Cannot resolve the reference because the href property has not been set.");
    }
    #endregion
}

1 个答案:

答案 0 :(得分:4)

这仅适用于您的泛型类型是接口,并且您使通用类型协变,即:IGeneric<out T>

请注意,这仅适用于接口或委托。有关详细信息,请参阅Covariance and Contravariance in Generics