2011-03-11 42 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