2013-02-27 74 views
16

我有很多對象,每個對象都有關於其類型的字符串信息。
喜歡:typeof:如何從字符串獲取類型

string stringObjectType = "DateTime"; 

在運行時,我沒有對象本身。
所以我不能測試它typeof (object)

我怎樣才能獲得,而通過運行對象的類型:

typeof (stringObjectType) 
+0

你將字符串作爲'DateTime'或'System.DateTime'嗎? – 2013-02-27 09:47:40

+0

這是你需要的嗎? http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx – Youssef 2013-02-27 09:50:04

+0

準確地說,你不能寫'typeof(object)'。你只能傳遞一個類名。改用'object.GetType'。只是說。 – RoadBump 2013-02-27 09:54:12

回答

16
try 
{ 
    // Get the type of a specified class. 
    Type myType1 = Type.GetType("System.DateTime"); 
    Console.WriteLine("The full name is {0}.", myType1.FullName); 
    // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException. 
    Type myType2 = Type.GetType("NoneSuch", true); 
    Console.WriteLine("The full name is {0}.", myType2.FullName); 
} 
catch(TypeLoadException e) 
{ 
    Console.WriteLine(e.Message); 
} 
catch(Exception e) 
{ 
    Console.WriteLine(e.Message); 
} 

Type.GetType(string) on MSDN

+0

是的,爲什麼他的代碼是正確的 – animaonline 2013-02-27 09:47:46

+2

雖然這段代碼是正確的。它回答他的問題嗎? string stringObjectType =「DateTime」;在這裏不會得到正確的類型。 – Evelie 2013-02-27 09:49:30

+0

我相信這只是一個例子 – animaonline 2013-02-27 09:50:08

18

您可以使用Type.GetType()得到一個類型來自它的字符串名稱。所以你可以這樣做:

Type DateType = Type.GetType("System.DateTime"); 

你不能只使用「DateTime」,因爲這不是類型的名稱。如果你這樣做,名稱是錯誤的(它不存在),那麼它會拋出異常。所以你需要嘗試一下。

您可以通過執行獲得任何給定對象的正確類型名稱:

string TypeName = SomeObject.GetType().FullName; 

如果您需要使用模糊或不完整的名字,那麼你將有一個有趣的時間與反思瞎搞。不是不可能的,但肯定是一種痛苦。