我正在寻找如何获取变量的编译时类型以进行调试。
可以简单地重现测试环境:
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>(T inputObject)
{
return typeof(T);
}
此方法将返回 System.Object
类型,因为泛型类型都是在编译时确定的。
只是补充一下,我假设您知道 typeof(object)
会给您 object
的编译时类型,如果您需要它只是硬编码的话在编译时。 typeof
不允许您传入变量以获取其类型。
此方法也可以作为扩展方法实现,以便与 object.GetType
方法类似地使用:
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
}
关于c# - 如何获取变量的编译时类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24906609/