![](/img/trans.png)
[英]Using an inherited generic type as an input to a method of a type constrained class
[英]Define method with Constrained Type Generic vs. Using Base Type
最近在工作中进行了讨论,我们试图辨别以下哪个更好。
我们的域有一个基本类型,许多类都继承自它:
public abstract class DomainBase
{
public int BaseId { get; set; }
}
在代码的另一个地方,我们有一个方法,它接受一组对象并根据BaseId
工作。 它不会返回对象,也不会使用给定的类型。
我的问题 :在这里使用泛型还是只接受基本类型更好?
选项A: void DoWork<TDomainBase>(List<TDomainBase> objects) where TDomainBase : DomainBase;
选项B: void DoWork(List<DomainBase> objects);
在我们的代码中,这些被称为相同,因为我们从不使用List<DomainBase>
中具有不同类型的new List<DomainBase> { new Foo(), new Bar() }
(例如new List<DomainBase> { new Foo(), new Bar() }
)。 我想说的是,使用泛型更好,这样,在将objects
传递给方法时,我们就不会隐式将objects
转换为其基类。 但是我想确保我不会在这里遗漏一些明显的东西。 (或者,不管我选择哪种选择,C#都可能在后台优化所有这些内容!)很高兴被证明是错误的。
编辑以删除不正确的语句。
“两个选项都应该起作用”-嗯,这几乎是正确的。
使用通用选项,您可以简单地将基本类型或从其派生的任何类型的列表直接传递给方法:
void DoWork<TDomainBase>(List<TDomainBase> objects) where TDomainBase : DomainBase
...
...
var list = new List<SomeClassDerivedFromDomainBase>() {/* initialize items */};
DoWork(list);
但是,使用基类列表,您将不得不执行一个额外的步骤,并从派生类型列表中生成该列表:
void DoWork(List<DomainBase> objects);
var list = new List<SomeClassDerivedFromDomainBase>() {/* initialize items */};
DoWork(list); // This will cause a compilation error:
// Cannot implicitly convert type 'System.Collections.Generic.List<SomeClassDerivedFromDomainBase>' to 'System.Collections.Generic.List<DomainBase>'
为什么我不能将List<Derived>
分配给List<Base>
的答案中解释了出现编译错误的原因?
要解决此问题,您将必须执行以下操作:
DoWork(list.ToList<DomainBase>());
我认为现在应该很清楚,在这种情况下,通用选项更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.