Possible to make a method with random type?
Greetings
I'm wondering if it is possible to create a single method with a random type.
Something like:
public static T CheckWhatTIs(object source)
{
MessageBox.Show("T = " + T.GetType());
}
where I would get "T = bool" when I use it as CheckWhatTIs(true); and get "T = int" when I use it as CheckWhatTIs开发者_开发知识库(1);
Is it possible to accomplish this ?
public static void CheckWhatTIs<T>(T source)
{
MessageBox.Show("T = " + source.GetType());
}
Few remarks:
- The function has no return type as you are just showing a message box
- If you want to use it as
CheckWhatTIs(1)
andCheckWhatTIs(true)
don't declare it as an extension method, removethis
from the parameters.
It depends whether you want to display the type of T
, or the type of the object that the parameter refers to.
Consider:
public static void ShowTypes<T>(T item)
{
Console.WriteLine("T = " + typeof(T));
Console.WriteLine("item.GetType() = " + item.GetType());
}
Now imagine:
ShowTypes<object>("foo");
That's entirely valid, but the type of T
is System.Object, whereas the type of the object is System.String.
You should also consider what you want to happen with:
ShowTypes<string>(null); // Will print System.String then explode
and
int? x = 10;
ShowTypes<int?>(x); // Will print System.Nullable<System.Int32>
// and then System.Int32
精彩评论