How to get compile time type of a variable?

2019-01-25 10:25发布

问题:

I'm looking for how to get compile time type of a variable for debugging purposes.

The testing environment can be reproduced as simply as:

object x = "this is actually a string";
Console.WriteLine(x.GetType());

Which will output System.String. How could I get the compile time type System.Object here?

I took a look over at System.Reflection, but got lost in the amount of possibilities it provides.

回答1:

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
}