从属性构造函数中获取应用了哪个属性的成员?

ryu*_*ice 17 .net c# reflection attributes

我有一个自定义属性,在我的自定义属性的构造函数中我想将我的属性的属性值设置为我的属性应用于的属性的类型,是否有某种程度来访问该属性应用于的成员从我的属性类里面?

Pau*_*ner 15

我担心属性不会这样.它们仅仅是"标记",附着在物体上,但无法与它们相互作用.

属性本身通常应该没有行为,只包含它们所附加类型的元数据.与属性关联的任何行为都应由另一个查找属性存在并执行任务的类提供.

如果您对应用该属性的类型感兴趣,那么该信息将在您反映获取属性的同时可用.


Nie*_*ter 10

.NET 4.5可以使用CallerMemberName:

[SomethingCustom]
public string MyProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后你的属性:

[AttributeUsage(AttributeTargets.Property)]
public class SomethingCustomAttribute : Attribute
{
    public StartupArgumentAttribute([CallerMemberName] string propName = null)
    {
        // propName = "MyProperty"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是前一段时间添加的,但我有一个后续问题:根据此链接 [https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information#member- [CallerMemberName] 仅提供成员名称,而不是完全限定的方式。因此,如果我想通过反射获取该类型,我怎样才能知道它的全名? (2认同)