Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取变量的编译时类型?_C#_.net_Types_Compile Time_Object Type - Fatal编程技术网

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

C# 如何获取变量的编译时类型?,c#,.net,types,compile-time,object-type,C#,.net,Types,Compile Time,Object Type,我正在寻找如何获取用于调试的变量的编译时类型 测试环境可以简单地复制为: object x = "this is actually a string"; Console.WriteLine(x.GetType()); 它将输出System.String。如何在此处获取编译时类型System.Object 我查看了一下系统。反射,但在它提供的大量可能性中迷失了方向。我不知道是否有一种内置的方法可以做到这一点,但下面的通用方法可以做到这一点: void Main() { object x

我正在寻找如何获取用于调试的变量的编译时类型

测试环境可以简单地复制为:

object x = "this is actually a string";
Console.WriteLine(x.GetType());
它将输出
System.String
。如何在此处获取编译时类型
System.Object


我查看了一下
系统。反射
,但在它提供的大量可能性中迷失了方向。

我不知道是否有一种内置的方法可以做到这一点,但下面的通用方法可以做到这一点:

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

public Type GetCompileTimeType<T>(T inputObject)
{
    return typeof(T);
}

你不能用var代替object吗?@DarrenYoung
var
是类型推断的语法糖,为了避免在局部变量声明中指定类型,它没有语义差异,在运行时也不会显示任何内容。@DarrenYoung他需要-他需要变量类型,不是要在运行时显示的变量值类型。我把他的问题理解为“变量的类型,而不是变量持有的对象的类型”。@DarrenYoung不,我相信他在问如何在运行时看到编译器在第1行中看到的类型,而不是在运行时实际存储在变量中的内容。OP想要的是编译时的类型,而不是运行时的类型。@DarrenYoung:不是,他没有说任何与此相关的内容。@DarrenYoung尽管名称有误导性,但此方法做的是OPwants@DarrenYoung:那是我的不好的名字。这将返回编译器认为变量是的类型,我认为它是所需要的类型。一开始我称之为错误的事情,因为我是一个小丑这也可以作为额外冷却的扩展方法。然后可以使用
x.GetCompileTimeType()
就像
x.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
}