如何建议稍后自动添加泛型类型?

How to suggest generic type added later automatically?

说明

  1. 在基础 class 中有一个名为“Add”的方法,它使用 要继承的 class 的通用类型。
  2. 基础 class 将用于 class 其他基础 class。
  3. Classes Base(2) 和 Base(3) 通常会做同样的事情,但是对于 Class Base(3),需要做额外的事情。
  4. 但是,class 中的“添加”方法将用于 classes Base(2) 和 Base(3)。
  5. T2 是一个枚举。

一切都很好,除了一件事我只是痴迷。

我的问题

“添加”方法实际上有多行代码。

感觉不对的解决方案

以后编辑“添加”方法的时候,感觉把所有继承的class都改一遍,感觉不对。

#region For T type
class Fruit { public string Name { get; set; } }
enum Books { None = 0, Love }
enum Sleeps { None = 0, Nightmare }
enum Months { None = 0, October }
#endregion


#region Class to inherit
abstract class Base<T1>
{
    internal void Add<T2>(T2 t2) { }
}
abstract class Base<T1, T2> : Base<T1> where T2 : Enum
{
    internal abstract T1 Where(int id);
}
abstract class Base<T1, T2, T3> : Base<T1, T2> where T2 : Enum where T3 : Enum
{
    internal abstract T1 Where(int id, T3 t3);
}
#endregion

#region Classes that can be used as objects. (Final)
class A : Base<Fruit, Months>
{
    public A()
    {
        Add(Months.October);
        Add(Sleeps.Nightmare); //X

        _ = Where(1);
    }

    internal override Fruit Where(int id)
    {
        throw new NotImplementedException();
    }
}
class B : Base<Fruit, Books, Sleeps>
{
    public B()
    {
        Add(Books.Love);
        Add(Months.October); //X

        _ = Where(1, Sleeps.Nightmare);
        _ = Where(1); //X
    }

    internal override Fruit Where(int id, Sleeps t3)
    {
        throw new NotImplementedException();
    }

    internal override Fruit Where(int id) //X
    {
        throw new NotImplementedException();
    }
}
#endregion

这里的问题似乎是您的解决方案没有 'feel right'。没关系,因为它实际上是正确的(除了不必要的继承)。你会感觉像是违反了 DRY 原则,但这是你能做的最好的事情。看看 .NET 创建者是如何使用 Action<>Tuple<> 等实现的。他们创建了新的 类,每个都有一个新的通用参数,但 Action<T1,T2> 不继承 Action<T1>,就像Base<T1,T2>不应该继承Base<T1>.