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 调用的方法获取属性的属性


- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01