【发布时间】: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