Use reflection to get attribute of a property via method called from the 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 调用的方法获取属性的属性
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01