Get value from custom attribute-decorated property?

后端 未结 2 1266
无人及你
无人及你 2021-02-13 20:05

I\'ve written a custom attribute that I use on certain members of a class:

public class Dummy
{
    [MyAttribute]
    public string Foo { get; set; }

    [MyAtt         


        
相关标签:
2条回答
  • 2021-02-13 20:39

    Your need to pass object itself to GetValue, not a property object:

    var value = prop.GetValue(o, null);
    

    And one more thing - you should use not .First(), but .FirstOrDefault(), because your code will throw an exception, if some property does not contains any attributes:

    object attr = (from row in propattr 
                   where row.GetType() == typeof(MyAttribute) 
                   select row)
                  .FirstOrDefault();
    
    0 讨论(0)
  • 2021-02-13 21:00

    You get array of PropertyInfo using .GetProperties() and call PropertyInfo.GetValue Method on each

    Call it this way:

    var value = prop.GetValue(o, null);
    
    0 讨论(0)
提交回复
热议问题