【问题标题】:Is there a way to "mark" properties of an object so they will "stand out" in reflection?有没有办法“标记”对象的属性,以便它们在反射中“突出”?
【发布时间】:2016-05-12 21:59:27
【问题描述】:

有没有办法“标记”对象的属性,以便它们在反射中“突出”?

例如:

class A
{
    int aa, b;
    string s1, s2;

    public int AA
    {
        get { return aa; }
        set { aa = value; }
    }

    public string S1
    {
        get { return s1; }
        set { s1 = value; }
    }

    public string S2
    {
        get { return s2; }
        set { s2 = value; }
    }
}

class B : A
{
    double cc, d;
    C someOtherDataMember;

    public C SomeOtherDataMember
    {
        get { return someOtherDataMember; }
    }

    public double CC
    {
        get { return cc; }
    }

    public double D
    {
        get { return d; }
        set { d = value; }
    }
}

class C
{...}

我希望能够仅对B 的数据成员进行操作,即标记它们,以便能够将它们与A 的成员区分开来。

像这样:

    B b = new B();
    var x = b.GetType().GetProperties();
    foreach (PropertyInfo i in x)
    {
        if (/*property is marked*/)
        {
            Console.WriteLine(i.Name);
        }
    }

如果它能够在没有对象实例的情况下工作,那就更好了,例如:

    var x = B.GetType().GetProperties();
    foreach (PropertyInfo i in x)
    {
        if (/*property is marked*/)
        {
            Console.WriteLine(i.Name);
        }
    }

有可能吗?

【问题讨论】:

  • 查看自定义属性。创建一个(或多个)对您来说意味着您想要的任何标记,然后注释您想要标记的那些成员。查找您要查找的成员的属性。查看解释和示例here at MSDN
  • stackoverflow.com/questions/3289198/…查看如何在属性上使用属性的示例
  • 如果要列出B声明的不继承的属性,可以使用直接反射;不需要自定义属性。

标签: c# reflection


【解决方案1】:

我希望能够仅对 B 的数据成员进行操作,即标记它们,以便能够将它们与 A 的成员区分开来。

可以使用自定义属性向成员添加元数据,但您不需要它。您可以使用直接反射。查看DeclaringType,如果不想创建实例,请使用typeof(B)

var x = typeof(B).GetProperties();
foreach (PropertyInfo i in x)
{
    if (i.DeclaringType == typeof(B))
    {
        Console.WriteLine(i.Name);
    }
}

您也可以在获取属性时应用该过滤器:

var x = typeof(B).GetProperties(BindingFlags.DeclaredOnly
                              | BindingFlags.Public
                              | BindingFlags.Instance);
foreach (PropertyInfo i in x)
{
    Console.WriteLine(i.Name);
}

【讨论】:

    【解决方案2】:

    您可以编写自定义属性,然后使用 GetCustomAttributes 方法检查属性。

    GetCustomAttributes

    例如

    foreach (PropertyInfo property in properties)
    {
        var ca = property.GetCustomAttributes(false);
    
        foreach (var attribute in ca)
        {
            if (attribute is YourAttribute)
            {
                            //...
            }
    
         }
    }
    

    【讨论】:

    • 添加一个例子会大大提高这个答案的质量。
    • 自定义属性非常适合向对象添加元数据,但在这种情况下,GetProperties 中的简单绑定规范可能更简单。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多