1

我看到一些 c# asp.net 源代码编写如下:

public class EntityInstanceContext<TEntityType> : EntityInstanceContext
{
    /// <summary>
    /// Initializes a new instance of the <see cref="EntityInstanceContext{TEntityType}"/> class.
    /// </summary>
    public EntityInstanceContext()
        : base()
    {
    }

谁能帮我理解为什么泛型类型是非泛型类型的子类?以这种方式设计有什么好处?

4

1 回答 1

2

.NET TypeSystem 是一个非常强大的系统。想象以下场景。我正在编写一个名为的类MyTuple,它是 BCLTuple类的编码不佳的克隆:

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

然后我意识到我想为该类型创建一种工厂类型的方法,以便我可以成功地挂接到类型推断系统中而不是指定T1T2当我不必这样时:

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(非泛型)
  • MyTuple < T1, T2 >

它们没有任何共同点,它们是不同的类型。

我可以说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

于 2013-09-18T11:14:12.767 回答