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

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

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

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

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/

相关文章:

c# - 现有连接被远程主机强制关闭

.net - 轻量级 .NET 调试器?

c# - Oauth 谷歌趋势下载 CSV 文件

c - 如何在C中创建基于字母的选项

Haskell:带条件的自定义类型

c# - 使方法异步后 HttpContext.Current.Session 为空

C#:反转句子中的单词

c# - 将键/值添加到现有 URL 字符串的最佳方法?

.net - MEF 的 CompositionContainer.ComposeParts -- 加载可以解决的任何内容,并忽略错误

php - 在 php 中上传 docx、zip、rar、pdf、ppt