使用反射的方法,通过从二传手叫了一个属性的属性 [英] Use reflection to get attribute of a property via method called from the setter

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

问题描述

注:这是一个后续的<一个href="http://stackoverflow.com/questions/3627659/what-ways-can-i-ensure-that-a-string-property-is-of-a-particular-length/3628000#3628000">answer在<一个href="http://stackoverflow.com/questions/3627659/what-ways-can-i-ensure-that-a-string-property-is-of-a-particular-length">$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找上的属性的而不是设置方法<属性/ EM>?

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.

这篇关于使用反射的方法,通过从二传手叫了一个属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆