I don't know if there is a built in way to do it but the following generic method would do the trick:
void Main()
{
object x = "this is actually a string";
Console.WriteLine(GetCompileTimeType(x));
}
public Type GetCompileTimeType<T>(T inputObject)
{
return typeof(T);
}
This method will return the type System.Object
since generic types are all worked out at compile time.
Just to add I'm assuming that you are aware that typeof(object)
would give you the compile time type of object
if you needed it to just be hardcoded at compile time. typeof
will not allow you to pass in a variable to get its type though.
This method can also be implemented as an extension method in order to be used similarly to the object.GetType
method:
public static class MiscExtensions
{
public static Type GetCompileTimeType<T>(this T dummy)
{ return typeof(T); }
}
void Main()
{
object x = "this is actually a string";
Console.WriteLine(x.GetType()); //System.String
Console.WriteLine(x.GetCompileTimeType()); //System.Object
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…