2011-03-11 33 views
1

問候可能使隨機類型的方法?

我想知道是否有可能創建一個隨機類型的單一方法。

喜歡的東西:

public static T CheckWhatTIs(object source) 
{ 
    MessageBox.Show("T = " + T.GetType()); 
} 

在那裏我會得到 「T =布爾」 當我使用它作爲CheckWhatTIs(真);當我將它用作CheckWhatTIs(1)時,得到「T = int」;

可以做到這一點嗎?

+3

想知道是什麼驅使你有這個! – Kangkan 2011-03-11 08:40:01

+0

在這種情況下,它可能沒有關係,但下一次:你不應該在擴展方法名稱中提到T,因爲調用者不知道T是什麼。那麼'true.ShowType()'怎麼樣? – 2011-03-11 08:46:24

+0

基本上我想這個信息來改變 (布爾)SomeObject to GetValue (SomeObject); – 2011-03-11 08:46:57

回答

6
public static void CheckWhatTIs<T>(T source) 
{ 
    MessageBox.Show("T = " + source.GetType()); 
} 

幾句話:

  1. 函數沒有返回類型,你只是顯示如果你想使用它作爲CheckWhatTIs(1)CheckWhatTIs(true)不聲明它作爲一個消息框
  2. 擴展方法,從參數中刪除this
+0

謝謝你,設法得到這個工作版本! – 2011-03-11 08:45:56

5

它取決於您是要顯示T的類型還是顯示參數引用的對象的類型。

考慮:

public static void ShowTypes<T>(T item) 
{ 
    Console.WriteLine("T = " + typeof(T)); 
    Console.WriteLine("item.GetType() = " + item.GetType()); 
} 

現在想象一下:

ShowTypes<object>("foo"); 

這是完全有效的,但T類型是System.Object的,而對象的類型是System.String。

你也應該考慮要使用發生的事情:

ShowTypes<string>(null); // Will print System.String then explode 

int? x = 10; 
ShowTypes<int?>(x); // Will print System.Nullable<System.Int32> 
        // and then System.Int32