简体   繁体   English

通过Reflection inside属性获取有关当前属性的信息

[英]Getting information on current property via Reflection inside attribute

I'm creating a custom attribute in C#. 我在C#中创建自定义属性。

So I have something like this: 所以我有这样的事情:

[AttributeUsage(AttributeTargets.Property)]
public class Something : Attribute
{
   public Something
   {
       Assembly a = Assembly.GetCallingAssembly();
   }
}

The code above will give me the assembly name of the assembly where the attribute is being called from. 上面的代码将为我提供调用属性的程序集的程序集名称。

What I would like to know is if there is a way to get the name and type of the property to which the attribute was added. 我想知道的是,是否有办法获取添加了属性的属性的名称和类型。 So as an example if I had: 举个例子,如果我有:

// This should return System.Int32 and MyString
[Something]
public int MyInt {get; set;}

// This should return me System.String, and MyString
[Something]
public string MyString {get; set;}

Is there any way to get those values upon adding the attribute, or will I have to resort to looping trough all the properties in the type and see which ones have an attribute assigned to them? 有什么方法可以在添加属性时获取这些值,或者我是否必须通过循环来遍历类型中的所有属性并查看哪些属性已分配给它们?

Thanks in advance. 提前致谢。

There is no other way then iterating over the properties and check the attributes. 没有其他方法可以迭代属性并检查属性。 But you should be able to do this in one Linq statement. 但你应该能够在一个Linq声明中做到这一点。

Use GetCustomAttributes on the GetProperties method of the types. 在类型的GetProperties方法上使用GetCustomAttributes

You could optimize the performance, if you mark all classes that use this attributes are marked by an interface, common base class or an class attribute. 如果标记所有使用此属性的类都由接口,公共基类或类属性标记,则可以优化性能。 So you could prefetch the classes instead to iterate over all types. 因此,您可以预取类而不是迭代所有类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM