0

如果我有:

[SomeAttr]
public Int32 SomeProperty
{
  get; set;
}

是否有可能SomeAttr告诉它附加在什么属性上?至少可以告诉它Typeproperty什么吗?

4

2 回答 2

0

不,你只能反过来做。您可以查询该属性(通过反射)它具有哪些属性:

Attribute.GetCustomAttributes(prop, true);

其中 prop 是派生自 MemberInfo 类的对象,描述了 SomeProperty 属性。接下来,您遍历返回的属性以查看它是否包含您的属性。

于 2013-05-17T13:01:14.947 回答
0

不,你不能。不是直接的。

在您收集属性的那一刻,您可以做的是使用额外信息设置该属性:

class SomeAttr: Attribute
{
    public PropertyInfo Target {get;set;}
}

...当您收集到信息时:

Type type = ... // The type which holds the property.
PropertyInfo propertyInfo = typeo.GetProperty("SomeProperty");
Type propertyType = propertyInfo.PropertyType;
SomeAttr attr = propertyInfo.GetCustomAttributes(false).OfType<SomeAttr>().FirstOrDefault();
attr.Target = propertyInfo; // <== Set the target information.

这样,您始终可以在代码的另一点检索其目标成员:

public void DoSomethingWithAttribute(SomeAttr attr)
{
    PropertyInfo whichProperty = attr.Target;
}

(也可以使用 baseclassMemberInfo来支持方法、字段等)

于 2013-05-17T12:58:40.147 回答