2017-05-24 343 views
2

我需要能夠在.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鏈接似乎已被破壞。

有什麼其他策略或技術可以用來檢索當前屬性的名稱?

非常感謝!

+4

怎麼樣nameof(MyProperty)? – mm8

回答

6

也許我完全誤解你的問題在這裏,但簡單地使用nameof運營商呢?

var propName = nameof(MyProperty); 
+0

我相信這種方法的挑戰是我必須在nameOf函數中包含屬性。我不確定如何從屬性本身獲得當前屬性的處理。 –

+0

確切的說法@ mm8表示:'nameof(MyProperty)'。您不需要掌握該屬性,這是編譯時,語言級別的事情。 –

相關問題