可以用随机类型制作方法吗?

The*_*der 1 c# silverlight types

问候

我想知道是否可以使用随机类型创建单个方法.

就像是:

public static T CheckWhatTIs(object source)
{
    MessageBox.Show("T = " + T.GetType());
}
Run Code Online (Sandbox Code Playgroud)

当我用它作为CheckWhatTIs时,我会得到"T = bool"(true); 当我用它作为CheckWhatTIs(1)时得到"T = int";

有可能做到这一点吗?

Dar*_*rov 6

public static void CheckWhatTIs<T>(T source)
{
    MessageBox.Show("T = " + source.GetType());
}
Run Code Online (Sandbox Code Playgroud)

几句话:

  1. 该函数没有返回类型,因为您只是显示一个消息框
  2. 如果要将其用作CheckWhatTIs(1)并且CheckWhatTIs(true)不将其声明为扩展方法,请this从参数中删除.


Jon*_*eet 5

这取决于您是否要显示T参数引用的对象的类型或类型.

考虑:

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

现在想象:

ShowTypes<object>("foo");
Run Code Online (Sandbox Code Playgroud)

这完全有效,但类型T是System.Object,而对象的类型是System.String.

您还应该考虑您想要发生的事情:

ShowTypes<string>(null); // Will print System.String then explode
Run Code Online (Sandbox Code Playgroud)

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