Use reflection to get attribute of a property via method called from the setter

后端 未结 3 1075
长发绾君心
长发绾君心 2021-01-03 03:48

Note: This is a follow-up to an answer on a previous question.

I\'m decorating a property\'s setter with an Attribute called TestMaxStringLength

3条回答
  •  一向
    一向 (楼主)
    2021-01-03 04:03

    As far as I know, there's no way to get a PropertyInfo from a MethodInfo of one of its setters. Though, of course, you could use some string hacks, like using the name for the lookup, and such. I'm thinking something like:

    var method = new StackTrace().GetFrame(1).GetMethod();
    var propName = method.Name.Remove(0, 4); // remove get_ / set_
    var property = method.DeclaringType.GetProperty(propName);
    var attribs = property.GetCustomAttributes(typeof(TestMaxStringLength), true);
    

    Needless to say, though, that's not exactly performant.

    Also, be careful with the StackTrace class - it's a performance hog, too, when used too often.

提交回复
热议问题