使用反射通过从 setter 调用的方法获取属性的属性

Use reflection to get attribute of a property via method called from the setter(使用反射通过从 setter 调用的方法获取属性的属性)

本文介绍了使用反射通过从 setter 调用的方法获取属性的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这是 answer 在 上一个问题.

我正在使用一个名为 TestMaxStringLength 的属性来装饰属性的 setter,该属性用于从 setter 调用以进行验证的方法中.

I'm decorating a property's setter with an Attribute called TestMaxStringLength that's used in method called from the setter for validation.

该属性当前如下所示:

public string CompanyName
{
    get
    {
        return this._CompanyName;
    }
    [TestMaxStringLength(50)]
    set
    {
        this.ValidateProperty(value);
        this._CompanyName = value;
    }
}

但我宁愿它看起来像这样:

But I would rather it look like this:

[TestMaxStringLength(50)]
public string CompanyName
{
    get
    {
        return this._CompanyName;
    }
    set
    {
        this.ValidateProperty(value);
        this._CompanyName = value;
    }
}

ValidateProperty负责查找setter属性的代码是:

The code for ValidateProperty that is responsible for looking up the attributes of the setter is:

private void ValidateProperty(string value)
{
    var attributes = 
       new StackTrace()
           .GetFrame(1)
           .GetMethod()
           .GetCustomAttributes(typeof(TestMaxStringLength), true);
    //Use the attributes to check the length, throw an exception, etc.
}

如何更改 ValidateProperty 代码以查找 property 上的属性而不是 set 方法?

How can I change the ValidateProperty code to look for attributes on the property instead of the set method?

推荐答案

据我所知,没有办法从它的 setter 之一的 MethodInfo 中获取 PropertyInfo.当然,您可以使用一些字符串技巧,例如使用名称进行查找等.我在想这样的事情:

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.

另外,小心使用 StackTrace 类 - 如果使用太频繁,它也会消耗性能.

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

这篇关于使用反射通过从 setter 调用的方法获取属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用反射通过从 setter 调用的方法获取属性的属性

基础教程推荐