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

Ben*_*ack 5 .net c# reflection attributes

注意:这是对前一个问题答案的后续跟进.

我正在使用一个属性来装饰一个属性的setter,这个属性被TestMaxStringLength称为在setter中调用的方法中用于验证.

该物业目前看起来像这样:

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

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

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

ValidateProperty用于查找setter属性的代码是:

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.
}
Run Code Online (Sandbox Code Playgroud)

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

小智 7

据我所知,没有办法从其中一个setter的MethodInfo获取PropertyInfo.当然,虽然你可以使用一些字符串黑客,比如使用查找名称等等.我想的是:

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);
Run Code Online (Sandbox Code Playgroud)

不用说,这并不是完全符合要求的.

另外,要小心StackTrace类 - 当经常使用时,它也是一种性能损耗.