Get value from custom attribute-decorated property?

后端 未结 2 1268
无人及你
无人及你 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();
    

提交回复
热议问题