如何获取变量的编译时间类型? [英] How to get compile time type of a variable?

查看:99
本文介绍了如何获取变量的编译时间类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for how to get compile time type of a variable for debugging purposes.

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

The testing environment can be reproduced as simply as:

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

哪个将输出 System.String 。我如何在这里得到 System.Object 的编译时间类型?

Which will output System.String. How could I get the compile time type System.Object here?

我看过 System.Reflection ,但却迷失了它提供的大量功能。

I took a look over at System.Reflection, but got lost in the amount of possibilities it provides.

推荐答案

我不知道是否有内置方法可以执行此操作,但是以下通用方法可以解决问题:

I don't know if there is a built in way to do it but the following generic method would do the trick:

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

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

此方法将返回 System.Object ,因为泛型类型都是在编译时确定的。

This method will return the type System.Object since generic types are all worked out at compile time.

只需添加一下,我假设您知道如果需要仅在编译时进行硬编码,typeof(object)将为您提供 object 的编译时类型。 typeof 不允许您传入变量以获取其类型。

Just to add I'm assuming that you are aware that typeof(object) would give you the compile time type of object if you needed it to just be hardcoded at compile time. typeof will not allow you to pass in a variable to get its type though.

此方法也可以实现作为扩展方法,以便与 object.GetType 方法类似地使用:

This method can also be implemented as an extension method in order to be used similarly to the object.GetType method:

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
}

这篇关于如何获取变量的编译时间类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆