如何获取变量的编译时类型?
我正在寻找如何为调试目的获取变量的编译时类型。
测试环境可以简单地再现:
object x = "this is actually a string"; Console.WriteLine(x.GetType());
哪个会输出System.String
。 我怎么能在这里获得编译时类型System.Object
?
我看了一下System.Reflection
,但却失去了它提供的可能性。
我不知道是否有内置方法可以做到这一点,但以下通用方法可以解决这个问题:
void Main() { object x = "this is actually a string"; Console.WriteLine(GetCompileTimeType(x)); } public Type GetCompileTimeType(T inputObject) { return typeof(T); }
此方法将返回System.Object
类型,因为generics类型都是在编译时解决的。
只是添加我假设你知道typeof(object)
会给你编译时类型的object
如果你需要它只是在编译时硬编码。 typeof
不允许您传入变量来获取其类型。
此方法也可以作为扩展方法实现,以便与object.GetType
方法类似地使用:
public static class MiscExtensions { public static Type GetCompileTimeType(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 }