2016-04-15 35 views
3

在C#中時,我有一個方法傳遞一個泛型類型「階級」只有有一個字符串

public string GetString<T>() where T : class 

在調用函數我有我想傳遞給GetString()<T>只有類的名稱。例如。 「我的課」。我如何將「MyClass」轉換爲class? 我試過用Type s,但找不到轉換。

編輯: 真正的例子是來自數據庫訪問類。 客戶端要求提供特定硬件組件的信息。該組件由字符串指定。基於這個字符串,我想訪問一個已知名稱模式的表。不硬編碼表名允許我們從數據庫添加/刪除表,而無需更改C#代碼。

返回所需信息的函數已經存在,需要一個class作爲泛型類型。

E.g.

string tblName = "HW_" + hwComponentFromClient; 
string retValue = GetString<GetClassByString(tblName)>(); 

我需要類似的方法:

class GetClassByString(string); 
+2

爲什麼你有一個班級的字符串?這似乎是真正的問題。爲什麼在編譯時不可能知道你想使用哪個類? –

+0

如果你在編譯時不知道類,你將不得不求助於反射或動態,這兩者都不是編譯時類型安全的。是否沒有可以投射到的基類或接口? –

回答

3

你可以得到的類名,但你必須從右邊裝配得到它,把類(組裝名+類名的全名,在我的情況下是"TestAlexander.Test")。

class Program 
{ 
    static void Main(string[] args) 
    { 
    Type classType = Assembly.GetExecutingAssembly().GetType("TestAlexander.Test"); 
    Test test = new Test(); 
    typeof(Test).GetMethod("TestMethod").MakeGenericMethod(classType).Invoke(test, null); 
    Console.Read(); 
    } 
} 
public class Test 
{ 
    public void TestMethod<T>() where T: class 
    { 
     Console.WriteLine("Great success!"); 
    } 
} 
+0

''instance'不一定與'classType'有關,就像你的情況一樣。所以很可能他已經有了「實例」(可能是'this'),我認爲提交者不需要'Activator.CreateInstance'。 –

+0

謝謝你的回答。我不需要調用一個方法。我只需要知道類名就可以得到泛型類'class'。另見我的編輯。 – telandor

+0

@telandor然後第一行應該做到這一點,那就是上課。要編輯 –

相關問題