繁体   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