有没有办法"标记"对象的属性,以便它们在反射中"脱颖而出"?

shi*_*zou 1 c# reflection

有没有办法"标记"对象的属性,以便它们在反射中"脱颖而出"?

例如:

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
{...}
Run Code Online (Sandbox Code Playgroud)

我希望能够B仅对数据成员采取行动,即标记它们,以便我能够将它们与成员区分开来A.

像这样:

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

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

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

有可能吗?

D S*_*ley 5

我希望能够仅对B的数据成员采取行动,即标记它们,以便我能够将它们与A的成员区分开来.

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

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

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

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