2013-03-11 72 views
3

的名字我有一個類如何獲得當前房地產

public class News : Record 
{ 
    public News() 
    { 
    } 

    public LocaleValues Name { get; set; } 
    public LocaleValues Body; 
} 

在我LocaleValues類我有:

public class LocaleValues : List<LocalizedText> 
{ 
    public string Method 
    { 
     get 
     { 
      var res = System.Reflection.MethodBase.GetCurrentMethod().Name; 
      return res; 
     } 
    } 
} 

我需要Method屬性返回的Name字符串表示物業名稱如下:

var propName = new News().Name.Method; 

我該如何做到這一點?感謝您的時間!

+2

http://stackoverflow.com/questions/4657311/reflection-get-property-name – SpaceBison 2013-03-11 07:29:32

+0

也許你想要的是_ [從getter/setter的'MethodInfo'中找到託管'PropertyInfo'](http://stackoverflow.com/questions/520138/)_? – 2013-03-11 09:47:36

+0

我不認爲這是可能的。 「LocaleValues」的一個實例如何知道它是通過一個名爲'Name'的屬性「找到」的?你可能每次都返回'get_Method'的代碼?也許你應該讓你的'Name' setter修改它所需的參數('value')來記錄名字? – 2013-03-11 09:54:13

回答

9

如果你真正的意思是當前財產(問題的標題):

public static string GetCallerName([CallerMemberName] string name = null) { 
    return name; 
} 
... 

public string Foo { 
    get { 
     ... 
     var myName = GetCallerName(); // "Foo" 
     ... 
    } 
    set { ... } 
} 

這推動工作的編譯器,而不是運行時,和作品無論內聯,模糊等。注意此需求using System.Runtime.CompilerServices;,C#5和.NET 4.5或類似文件的using指令。

如果你指的是例如:

var propName = new News().Name.Method; 

那麼它是不可能直接從語法; .Name.Method()會調用.Name的結果(可能是擴展方法) - 但這只是一個其他對象,並不知​​道它來自哪裏(如Name屬性)。理想情況下得到Name,表達式樹是最簡單的方法。

Expression<Func<object>> expr =() => new News().Bar; 

var name = ((MemberExpression)expr.Body).Member.Name; // "Bar" 

可能被封裝爲:

public static string GetMemberName(LambdaExpression lambda) 
{ 
    var member = lambda.Body as MemberExpression; 
    if (member == null) throw new NotSupportedException(
      "The final part of the lambda is not a member-expression"); 
    return member.Member.Name; 
} 

Expression<Func<object>> expr =() => new News().Bar; 
var name = GetMemberName(expr); // "Bar" 
+0

也許我不明白的東西....或在我的問題中發佈了錯誤,但我怎麼能用它來知道'LocaleValues'內我的屬性的確切名稱?我需要這樣做,當我調用'News.Name.Method'時,'LocalValues'知道它被命名爲'Name',當我調用'News.Body.Method'時,它比callea爲'Body',與具有類型的屬性的其他類完全一樣的東西'LocalValues' ......我真的爲我的英語不好:( – CodeDemen 2013-03-11 09:15:59

+0

對不起這是MVVM在WPF說'NotifyPropertyChanged特別有用的,而不是( 「Foo」)'你可以使用這個屬性並且只是說'NotifyPropertyChanged()'。 – 2016-07-03 23:21:11