我想知道是否有可能创建一个随机类型的单一方法。
喜欢的东西:
public static T CheckWhatTIs(object source)
{
MessageBox.Show("T = " + T.GetType());
}
在那里我会得到 “T =布尔” 当我使用它作为CheckWhatTIs(真);当我将它用作CheckWhatTIs(1)时,得到“T = int”;
可以做到这一点吗?
我想知道是否有可能创建一个随机类型的单一方法。
喜欢的东西:
public static T CheckWhatTIs(object source)
{
MessageBox.Show("T = " + T.GetType());
}
在那里我会得到 “T =布尔” 当我使用它作为CheckWhatTIs(真);当我将它用作CheckWhatTIs(1)时,得到“T = int”;
可以做到这一点吗?
public static void CheckWhatTIs<T>(T source)
{
MessageBox.Show("T = " + source.GetType());
}
几句话:
CheckWhatTIs(1)
和CheckWhatTIs(true)
不声明它作为一个消息框this
。谢谢你,设法得到这个工作版本! – 2011-03-11 08:45:56
它取决于您是要显示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
想知道是什么驱使你有这个! – Kangkan 2011-03-11 08:40:01
在这种情况下,它可能没有关系,但下一次:你不应该在扩展方法名称中提到T,因为调用者不知道T是什么。那么'true.ShowType()'怎么样? – 2011-03-11 08:46:24
基本上我想这个信息来改变 (布尔)SomeObject to GetValue(SomeObject); –
2011-03-11 08:46:57