c# - .NET Core 1.1 如何获取当前属性的名称

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

我需要能够访问 .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 又如何呢?运营商?

var propName = nameof(MyProperty);

关于c# - .NET Core 1.1 如何获取当前属性的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163259/

相关文章:

c# - 日期转换错误

c# - 将 IUnitOfWork 注册为 .net 核心中的服务

c# - Date/Time Insert in Ms access through c# Access

c# - 拆分字符串数组

c# - 一个查询的结果不能被多次枚举异常

c# - 在特定时区创建 DateTime 然后转换为 utc

c# - ASP.Net core Azure Webjob (SDK 3.0.10) DI 无法解析

c# - 有效使用StringBuilder

c# - 在另一个 AppDomain 中调用 Await 时没有 SynchronizationContext

c# - ThreadPool.QueueUserWorkItem - 订单未保留?