开发者

.NET : Get property name in attribute

开发者 https://www.devze.com 2022-12-29 12:12 出处:网络
[MyAttribute()] public string Name { get; set; } In MyAttribute I need to know the name of associated 开发者_Python百科property, is it possible?
[MyAttribute()]
public string Name { get; set; }

In MyAttribute I need to know the name of associated 开发者_Python百科property, is it possible?

EDIT:

I need to use it in text formatting.


No, this is not possible. Usually you would use reflection to read attributes applied on a given property, so you already know the property. Example:

var properties = typeof(SomeType).GetProperties();
foreach (var property in properties)
{
    var attributes = property.GetCustomAttributes(typeof(MyAttribute), true);
    if (attributes.Count > 0)
    {
        // look at property.Name here
    }
}


You can use a PostSharp aspect to do the job. I had a similar question a while back, which was almost the same thing. You can see comments on the answer for more info about some of the implications that you might encounter.

0

精彩评论

暂无评论...
验证码 换一张
取 消