1

This is my sample code.

public class Sample
{
    public void Main()
    {
        Execute01<DB_MS_A>();
        Execute02<DB_MS_A>();

        Execute01<DB_MS_B>();
        Execute02<DB_MS_B>();

        Execute01<DB_MS_C>();
        Execute02<DB_MS_C>();
    }
           
    public void Execute01<DbModel>()
        where DbModel : IDatabaseModel
    {
        // do something...
    }

    public void Execute02<DbModel>()
        where DbModel : IDatabaseModel
    {
        // do something...
    }
}

Not to waste code lines, I want to modify Main method code like below.

    public void Main()
    {
        var dbList = new List<dynamic>() {
            DB_MS_A,
            DB_MS_B,
            DB_MS_C
        };

        dbList.ForEach(db => {
            Execute01<db>();
            Execute02<db>();
        });
    }

But it seems impossible to add static value to List. Also Delivering static value as lambda arguments is not possible.

Is there any way for method Refactoring?

ha2pa1
  • 25
  • 3

1 Answers1

0

I think you can simply use a list of type:

var listInputType = new []{
        typeof(string), 
        typeof(int),
}; 

But I don't think you can pass run time type to generique as they need compile type.
But we can use reflexion like in this SO question: C# use System.Type as Generic parameter.

public class Program
{
    public static void Main()
    {
        var listInputType = new []{
                typeof(string), 
                typeof(int),
        }; 
        
        foreach(var myType in listInputType){
            typeof(Program).GetMethod("M1").MakeGenericMethod(myType).Invoke(null, null);
            typeof(Program).GetMethod("M2").MakeGenericMethod(myType).Invoke(null, null);
        }
    }

    public static void M1<t>()
    {
        Console.WriteLine($"M1<{typeof(t).Name}>()");
    }

    public static void M2<t>()
    {
        Console.WriteLine($"M2<{typeof(t).Name}>()");
    }
}

C# online demo

Self
  • 349
  • 1
  • 8
  • Can't comment on the question: https://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class, the comment on this question may help it to be more readable. But you will have to change `M1()` signature to `M1(t inputType)`. – Self Dec 30 '20 at 08:45