Home > other >  How to suggest generic type added later automatically?
How to suggest generic type added later automatically?

Time:10-23

explanation

  1. In the base class there is a method called "Add" which uses the generic type of a class to inherit.
  2. The base class will be used for class other Base classes.
  3. Classes Base(2) and Base(3) will generally do the same things, but for Class Base(3), extra things need to be done.
  4. However, the "Add" method in the base class will be used for classes Base(2) and Base(3).
  5. T2 is an enum.

Everything works fine except for one thing I'm just obsessed with.

my issue

  • The parameter of type generic in the "add" method has no restrictions.
  • Visual studio doesn't automatically suggest me the type I specified for T2.

The "Add" method actually has multiple lines of code.

solutions that don't feel right

  • So I don't want to add "Add" method as copy-paste for Base(2) and Base(3).
  • to recreate the method for classes Base(2) and Base(3) and add "base.Add();" to its content.

It doesn't feel right to fix all the inherited classes again when editing the "Add" method in the future.

#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

enter image description here

enter image description here

CodePudding user response:

The issue here seems to be that your solution doesn't 'feel right'. That's ok because it actually is right (besides the unnecessary inheritance). You are going to have what feel like DRY principle violations, but that is the best you can do. Look at how .NET creators did it with Action<> and Tuple<>, etc. They created new classes, each with a new generic parameter, but Action<T1,T2> does not inherit Action<T1>, just like Base<T1,T2> should not inherit Base<T1>.

  • Related