簡體   English   中英

如何在C#中使用反射來區分具有相同屬性的類成員

[英]How to distinguish class members with same attribute using reflection in C#

編輯:為了清楚地闡明我的問題,我問了一個新問題


編輯:因為反射解決方案是不可能的,所以我將標題更改為“有沒有辦法在C#中獲取變量名?” “如何在C#中使用反射來區分具有相同屬性的類成員”


編輯:變量名稱不是一個准確的含義,我的目標是

  • 如果可能的話,使用反射來獲取變量名(有人已經告訴我這是不可能的)。
  • 在任何情況下(例如在CheckMethod中)聲明成員時,請使用解決方案來獲取添加的信息。

我以為可以使用Reflection獲取變量信息,包括其名稱,但是不起作用。

 public class C { public List<string> M1{get; set;} public List<string> M2{get; set;} } static void Main(string[] args) { C c = new C(); CheckMethod(c.M1); ChekcMethod(c.M2); } void CheckMethod(List<string> m) { //Want to get the name "M1" or "M2", but don't know how Console.Write(m.VariableName); } 

然后,我認為屬性可能是解決方案。

public class C
{
    [DisplayName("M1")]
    public List<string> M1{get; set;}
    [DisplayName("M2")]
    public List<string> M2{get; set;}
}

static void Main(string[] args)
{
    C c = new C();
    CheckMethod(c.M1);
    ChekcMethod(c.M2);
}

void CheckMethod(List<string> m)
{
    //Find all properties with DisplayNameAttribute
    var propertyInfos = typeof(C)
            .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
                           | BindingFlags.GetField | BindingFlags.GetProperty)
            .FindAll(pi => pi.IsDefined(typeof(DisplayNameAttribute), true));
    foreach (var propertyInfo in propertyInfos)
    {
        //I can get the DisplayName of all properties, but don't know m is M1 or M2

    }
}
  • 是否有任何本機反射方式來獲取變量的名稱? 不可能
  • 如何確定方法參數代表哪個成員變量?

我正在使用Unity3D,因此.net版本是3.5

使用反射是不可能的。 編譯變量名稱將不存在之后,因此您無法在運行時使用反射來獲取名稱。 還有其他一些方法,例如表達式樹和閉包。 如果可以使用它們,請嘗試此操作。

static string GetVariableName<T>(Expression<Func<T>> expr)
{
    var body = (MemberExpression)expr.Body;

    return body.Member.Name;
}

要使用這種功能,您可以做

GetVariableName(() => someVar)

並且,如果您使用的是C#6,則添加了新的nameof keyworkd。 更多信息

https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

您可以使用nameof(anyVariable) ,它應該以字符串形式返回任何變量的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM