如何获取变量的编译时类型?

jol*_*olt 9 .net c# types compile-time object-type

我正在寻找如何为调试目的获取变量的编译时类型.

测试环境可以简单地再现:

object x = "this is actually a string";
Console.WriteLine(x.GetType());
Run Code Online (Sandbox Code Playgroud)

哪个会输出System.String.我怎么能System.Object在这里获得编译时间类型?

我看了看System.Reflection,但迷失了它提供的可能性.

Chr*_*ris 18

我不知道是否有内置方法可以做到这一点,但以下通用方法可以解决这个问题:

void Main()
{
    object x = "this is actually a string";
    Console.WriteLine(GetCompileTimeType(x));
}

public Type GetCompileTimeType<T>(T inputObject)
{
    return typeof(T);
}
Run Code Online (Sandbox Code Playgroud)

此方法将返回类型,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
}
Run Code Online (Sandbox Code Playgroud)

  • @DarrenYoung尽管名称具有误导性,但这种方法可以满足操作需要 (2认同)
  • @Dai: typeof 不能对变量起作用,尽管这是我将 OP 解释为想要的。他有一个变量 x 并且想知道编译器认为它是什么。 (2认同)
  • @DarrenYoung:这是我命名的不好.这将返回编译器认为变量的类型,这是我认为需要的类型.我最初称它为错误的东西,因为我是个小丑.;-) (2认同)
  • 这也可以作为额外凉爽的延伸方法.然后你可以像`x.GetType()`一样使用`x.GetCompileTimeType()`. (2认同)