【问题标题】:How to get compile time type of a variable?如何获取变量的编译时类型?
【发布时间】:2014-09-14 09:48:34
【问题描述】:

我正在寻找如何获取变量的编译时间类型以进行调试。

测试环境可以简单的复制如下:

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

这将输出System.String。我怎么能在这里得到编译时类型System.Object

我查看了System.Reflection,但对它提供的可能性感到迷茫。

【问题讨论】:

  • 不能用var代替object吗?
  • @DarrenYoung var 是类型推断的语法糖,以避免在局部变量声明中指定类型,它没有语义差异,也没有在运行时显示任何内容。
  • @DarrenYoung 他愿意 - 他希望在运行时显示变量类型,而不是变量值类型。
  • 我把他的问题读作“变量的类型,而不是变量所持有的对象的类型”。
  • @DarrenYoung 不,我相信他问的是如何在 run-time 中查看编译器在第 1 行看到的类型,而不是实际存储在变量中的内容运行时。

标签: c# .net types compile-time object-type


【解决方案1】:

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

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
}

【讨论】:

  • OP 想要编译时的类型而不是运行时的类型。
  • @DarrenYoung 尽管名称具有误导性,但此方法可以满足操作人员的要求
  • @Dai: typeof 不能对变量起作用,尽管这是我将 OP 解释为想要的。他有一个变量 x,想知道编译器认为它是什么。
  • @DarrenYoung:那是我命名的错误。这将返回编译器认为变量的类型,这是我认为需要的。我最初称它为错误的东西,因为我是一个小丑。 ;-)
  • 这也可以作为额外凉爽的扩展方法。然后你可以像x.GetType()一样使用x.GetCompileTimeType()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 2012-08-03
  • 2012-07-03
  • 2016-12-03
相关资源
最近更新 更多