是nameof()在编译时评价? [英] Is nameof() evaluated at compile-time?

查看:249
本文介绍了是nameof()在编译时评价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#6,您可以使用 nameof()运营商获取包含变量或类型的名称的字符串。

In C# 6, you can use a nameof() operator to get a string containing the name of a variable or a type.

这是在编译时进行计算,或者通过某种罗斯林API运行?

Is this evaluated at compile-time, or at runtime via some Roslyn API?

您可以阅读有关在 nameof()运营商官方讨论接受的答案指出,或dedicated后在我的博客这里你可以找到一个描述和它的用法的。

You can read about the nameof() operator at the official discussion pointed out in the accepted answer, or the dedicated post at my blog. Here you can find a description and example of its use.

推荐答案

是的。 nameof()是在编译时进行计算。纵观最新版的规格的:

Yes. nameof() is evaluated at compile-time. Looking at the latest version of the specs:

的nameof前pression是一个常数。在所有情况下,nameof(...)是是在编译时评估,以生成一个字符串。它的参数是不是在运行时进行评估,被认为是不可到达code(但它不发出一个不可达code的警告)。

The nameof expression is a constant. In all cases, nameof(...) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an "unreachable code" warning).

nameof运营商 - V5

您可以看到,<一个href=\"http://tryroslyn.azurewebsites.net/#b:master/K4Zwlgdg5gBAygTxAFwKYFsDcAoADsAIwBswBjGUogQxBBgDEB7R7Ab2xk5n2LJgDdGYACYwAQlQBOACgCUHLuy7KYAYUYQQjIqgB0AdUlg0AGUippEKulSMAZtKaNZsnMoC+2d0AAA=\">this TryRoslyn例如的,其中这样的:

You can see that with this TryRoslyn example where this:

public class Foo
{
    public void Bar()
    {
        Console.WriteLine(nameof(Foo));
    }
}

编译和反编译成这样:

Is compiled and decompiled into this:

public class Foo
{
    public void Bar()
    {
        Console.WriteLine("Foo");
    }
}

其运行时当量为:

Its run-time equivalent is:

public class Foo
{
    public void Bar()
    {
        Console.WriteLine(typeof(Foo).Name);
    }
}


正如在评论中提到的,这意味着,当你在一个泛型类型使用 nameof 的类型参数不指望得到实际使用的动态类型的名称作为一个类型参数,而不是仅仅的类型参数的名称。因此,这:


As was mentioned in the comments that means that when you use nameof on type parameters in a generic type don't expect to get the name of the actual dynamic type used as a type parameter instead of just the type parameter's name. So this:

public class Foo
{
    public void Bar<T>()
    {
        Console.WriteLine(nameof(T));
    }
}

将成为这样的:

public class Foo
{
    public void Bar<T>()
    {
        Console.WriteLine("T");
    }
}

这篇关于是nameof()在编译时评价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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