【问题标题】:How to get the name of the current property in .NET Core 1.1如何在 .NET Core 1.1 中获取当前属性的名称
【发布时间】:2017-05-24 15:55:21
【问题描述】:

我需要能够访问 .NET Core 中类的当前属性的名称。

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get => _myProperty;
        set
        {
            // GOAL: Check my property name and then do something with that information. 

            // The following used to works in the full .NET Framework but not .NET Core.
            // var propName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            _myProperty = value;
        }
    }
}

在完整的 .NET Framework 中,我们可以只使用反射,如下所示。

System.Reflection.MethodBase.GetCurrentMethod().Name;

(我们记得一个属性实际上只是一个底层的方法。)

但是,.NET Core 1.1 中似乎没有此功能 - 尽管它(可能/将)在 .NET Standard 2.0 中可用。

在这个 GitHub 问题 (https://github.com/dotnet/corefx/issues/12496) 上,有一个使用 GetMethodInfoOf 访问属性名称的参考。但是,我一直无法找到此方法的任何示例,并且指向可能示例的 GitHub 链接似乎已损坏。

可以使用什么其他策略或技术来检索当前属性的名称?

非常感谢!

【问题讨论】:

  • nameof(MyProperty) 怎么样?

标签: c# .net .net-core system.reflection


【解决方案1】:

也许我在这里完全误解了您的问题,但是简单地使用 nameof 运算符呢?

var propName = nameof(MyProperty);

【讨论】:

  • 我相信这种方法的挑战是我必须在 nameOf 函数中包含该属性。我不确定如何从属性本身获取当前属性的句柄。
  • 就像@mm8 所说的那样:nameof(MyProperty)。您不需要处理属性,这是编译时语言级别的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多