2

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

我得到的错误信息是:

值“Reference 1[Dog]" is not of type "Reference1[Pet]”不能用于此通用集合。

我的参考类如下所示:

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
}
4

1 回答 1

4

这仅在您的泛型类型是接口并且您使泛型类型协变时才有效,即:IGeneric<out T>

请注意,这仅适用于接口或委托。有关详细信息,请参阅泛型中的协变和逆变

于 2013-08-15T20:21:50.077 回答