Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c# - How to get compile time type of a variable?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...