gpt4 book ai didi

c# - 类和方法级别泛型类型约束交互

转载 作者:太空狗 更新时间:2023-10-29 18:27:45 26 4
gpt4 key购买 nike

考虑以下类:

public class DerivedClassPool<TBase> where TBase : class
{
public TBase Get(Type componentType)
{
// Not important, but you get the idea
return Activator.CreateInstance(componentType) as TBase;
}

public TDerived SomeMethod<TDerived>() where TDerived : TBase
{
return Get(typeof(TBase)) as TDerived;
}
}

请注意,我已将 TBase 泛型类参数限制为一个类:where TBase : class
我还将 TDerived 泛型方法参数限制为 TBase 或从中派生的东西:where TDerived : TBase

我在 as TDerived 行收到错误:

The type parameter 'TDerived' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint

我知道为了防止错误,我需要添加约束 class,所以我会得到:

where TDerived : class, TBase

TBase 已经被限制为一个类并且 TDerived 被限制为一个 TBase 时,为什么我必须这样做> 还是派生自它?

最佳答案

更新:这个问题是 the subject of my blog on September 19th, 2011 .感谢您提出很好的问题!


Why do i have to do this when TBase is already constrained to be a class and TDerived is constrained to be a TBase or derived from it?

因为值类型可以从引用类型派生。 int派生自引用类型 objectSystem.ValueType并实现了一些接口(interface)。那不会使 int引用类型。

您调用SomeMethod<int> 是完全合法的在 DerivedClassPool<object> 的实例上因为 int 是从对象派生的。

现在, 情况下您的批评是有道理的。可以构造两个类型参数以这样一种方式相关的情况,即它们在逻辑上只能是引用类型,但只有其中一个被语言归类为“已知为引用类型”。

作为读者的练习:你能找到一个吗?可能需要仔细阅读规范的第 10.1.5 节以获得“已知为引用类型”的准确定义。

关于c# - 类和方法级别泛型类型约束交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8898440/

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