gpt4 book ai didi

c# - 如何将 Generic 转换为 Generic,其中 T 是 R 的子类?

转载 作者:行者123 更新时间:2023-11-30 20:55:30 24 4
gpt4 key购买 nike

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

我得到的错误信息是:

The value "Reference1[Dog]" is not of type "Reference1[Pet]" and cannot be used in this generic collection.

我的引用类是这样的:

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
}

最佳答案

只有当你的泛型类型是一个接口(interface),并且你让你的泛型类型协变时,这才有效,即:IGeneric<out T> .

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

关于c# - 如何将 Generic<T> 转换为 Generic<R>,其中 T 是 R 的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com