我需要能夠在.NET Core的類中訪問當前屬性的名稱。如何在.NET Core 1.1中獲取當前屬性的名稱
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 1.1核心可用 - 儘管它(可以/會)在.NET標準2.0中可用。
在此GitHub問題(https://github.com/dotnet/corefx/issues/12496)上,提到使用GetMethodInfoOf
來訪問屬性名稱。但是,我一直無法找到這種方法的任何示例,並且指向可能示例的GitHub鏈接似乎已被破壞。
有什麼其他策略或技術可以用來檢索當前屬性的名稱?
非常感謝!
怎麼樣nameof(MyProperty)? – mm8