[英]self-referencing generic inheritance in c#
我看到一些c#asp.net源代码编写如下:
public class EntityInstanceContext<TEntityType> : EntityInstanceContext
{
/// <summary>
/// Initializes a new instance of the <see cref="EntityInstanceContext{TEntityType}"/> class.
/// </summary>
public EntityInstanceContext()
: base()
{
}
谁能帮助我了解为什么泛型类型是从非泛型类型继承的? 用这种方式设计的好处是什么?
.NET TypeSystem是一个非常强大的系统。 想象以下情况。 我正在编写一个名为MyTuple
的类,它是BCL Tuple
类的一个编码较差的克隆:
public class MyTuple<T1, T2> {
public T1 Item1 { get; private set; }
public T2 Item2 { get; private set; }
public MyTuple(T1 item1, T2 item2) {
this.Item1 = item1;
this.Item2 = item2;
}
}
然后我意识到我想为该类型创建一种工厂方法 ,以便我可以成功地挂接到类型推断系统中,而不必在不需要时指定T1
和T2
:
new MyTuple<int, string>(123, "test"); // which is also a bit redundant
因此,我正在写我在一个类中谈论的方法,我们将其称为Factory
类:
public class Factory {
public static MyTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) {
return new MyTuple<T1, T2>(item1, item2);
}
}
这样,我在写作时会更快乐:
var tuple = Factory.Create(123, "test"); // and tuple is inferred to be of <int, string>
现在,如果将Factory
重命名为MyTuple
会发生什么:
public class MyTuple {
public static MyTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) {
return new MyTuple<T1, T2>(item1, item2);
}
}
简而言之: 没什么不好
我现在有2个完全不同的类型就是这种情况:
它们没有共同点,它们是不同的类型。
我是否可以说MyTuple<T1, T2>
恰好扩展了MyTuple
? 好吧,只要MyTuple
既不是static
也不是sealed
, 是的,可以 !
public class MyTuple { ... }
public class MyTuple<T1, T2> : MyTuple { ... }
因此,就您而言,仅是Mammal
扩展了Animal
或... Tiger
扩展了Mammal
。 这不像Mammal of a weirder sort
Mammal of a good ol' classical sort
扩展Mammal of a good ol' classical sort
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.