How to get a custom attribute from object instance in C#

前端 未结 6 1176
眼角桃花
眼角桃花 2020-12-05 07:40

Let\'s say I have a class called Test with one property called Title with a custom attribute:

public class Test
{
    [DatabaseField(\"title\")]
    public s         


        
6条回答
  •  遥遥无期
    2020-12-05 08:05

    It is, but ultimately it's going to be a roundabout way, since you will get the Type instance from calling GetType on your instance that exposes the property, and then work on that(more often than not).

    In this specific case, your extension method isn't going to be able to get the attribute information because all you are passing to it is a string.

    Ultimately, what you need is something to get the PropertyInfo for the property from. Other answers are referring to the Type, what they lack is, this is not the only way to get the attribute information at the PropertyInfo which you want.

    You can do that by passing a Type instance with a string, presumably, with the property name, so you can call GetProperty on the Type.

    Another way of doing this since C# 3.0 has been to have a method that takes an Expression and then use the parts of the Expression to get at the PropertyInfo. In this case, you would take an Expression> or something where TResult is string.

    Once you have the PropertyInfo, you can call GetCustomAttributes on it, and look for your attribute.

    The advantage to the expression approach is that Expression derives from LambdaExpression, which you can call Compile on, and then call to get the actual value, if you need it.

提交回复
热议问题