使用反射的方法,通过从二传手叫了一个属性的属性属性、叫了、反射、方法

2023-09-03 13:34:53 作者:村里的网红

注:这是一个后续的answer在$p$pvious问题 的。

我在装饰性的设置方法与称为属性 TestMaxStringLength 就是使用的方法从模子进行验证调用。

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

该物业目前看起来是这样的:

The property currently looks like this:

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;
    }
}

在$ C $下 ValidateProperty ,负责查找二传手的属性是:

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 code找上的属性的而不是设置方法?

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

推荐答案

据我所知,有没有办法从它的制定者之一的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.

另外,要注意的堆栈跟踪类 - 这是一个性能猪,太,在使用时往往

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