2016-03-04 87 views
4

是否有可能讓這樣的代碼工作?:使用變量類型

private List<Type> Models = new List<Type>() 
    { 
     typeof(LineModel), typeof(LineDirectionModel), typeof(BusStopTimeModel), typeof(BusStopNameModel) 
    }; 

    foreach (Type model in Models) // in code of my method 
    { 
     Connection.CreateTable<model>(); // error: 'model' is a variable but is used like a type 
    } 

在此先感謝

+0

肯定的,但有這樣的沒有簡單的方法。出於性能原因,我建議你爲所有需要的類型編寫所有代碼。我認爲有反思的方式,但這會很慢並且不容易實施。 –

+1

你必須使用反射的'MakeGenericMethod'。可能有更好的方法來做你想做的事。但是,你可以。 – Jonesopolis

+0

'CreateTable '我應該工作。 – 2016-03-04 19:29:34

回答

2

您將無法使用變量作爲使用傳統語法的通用型( CreateTable<model>)。不知道什麼CreateTable呢,你有兩個選擇:

  1. 而不是使CreateTable泛型方法,有它需要的類型作爲參數:

    public static void CreateTable(Type modelType) 
    { 
    } 
    
  2. 使用反射動態調用通用方法,使用所期望的類型:

    var methodInfo = typeof (Connection).GetMethod("CreateTable"); 
    foreach (Type model in Models) 
    { 
        var genericMethod = methodInfo.MakeGenericMethod(model); 
        genericMethod.Invoke(null, null); // If the method is static OR 
        // genericMethod.Invoke(instanceOfConnection, null); if it's not static 
    } 
    

請注意,反射方式會比較慢,因爲直到運行時纔會解析方法信息。

+0

正是因爲它是慢,你應該移動'typeof運算(連接).GetMethod(「CREATETABLE」)'外'foreach',只叫'MakeGenericMethod'和'Invoke'內。 – xanatos

+0

@xanatos好點,修改。 – PoweredByOrange

0

你可以像這樣做,

private List<Type> Models = new List<Type>() 
{ 
    typeof(LineModel), typeof(LineDirectionModel), typeof(BusStopTimeModel), typeof(BusStopNameModel) 
}; 

void SomeMethod() 
{ 
    MethodInfo genericFunction =Connection.GetType().GetMethod("CreateTable"); 

    foreach (Type model in Models) 
    { 
    MethodInfo realFunction = genericFunction.MakeGenericMethod(model); 
    var ret = realFunction.Invoke(Connection, new object[] { }); 
    } 
}