gpt4 book ai didi

c# - 有没有一种方法可以“标记”对象的属性,使它们在反射中“突出”?

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:32 30 4
gpt4 key购买 nike

有没有一种方法可以“标记”对象的属性,使它们在反射中“突出”?

例如:

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);
}
}


有可能这样做吗?

最佳答案

我只希望能够对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);
}

关于c# - 有没有一种方法可以“标记”对象的属性,使它们在反射中“突出”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37198166/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com