您在现实世界中将自定义 .NET 属性用于哪些方面?
What kind of things have you used custom .NET attributes for in the real world?
我已经阅读了几篇关于它们的文章,但我从未使用过自定义属性.
I've read several articles about them, but I have never used custom attributes.
我觉得当它们有用时我可能会忽略它们.
I feel like I might be overlooking them when they could be useful.
我说的是您创建的属性,而不是已经包含在框架中的属性.
I am talking about attributes that you create, not ones that are already included in the framework.
我已经使用它们自定义"属性进行验证(即使用我自己的信用卡验证"标记要验证的字段)和自定义 LinqToLucene 分析器我已经写过(即指定在给定字段上使用哪个分析器).
I've used them "custom" attributes for validation (ie. marking a field to be validated with my own "credit card validation") and custom LinqToLucene analyzers I've written (ie. specifying which analyzer to use on a given field).
例如,验证代码如下所示:
The validation code, for example, would look something like this:
public class Customer
{
[CreditCardValidator]
string creditCardNumber;
[AddressValidator]
string addressLineOne
}
验证上述对象时,由于自定义"属性,每个字段都使用适当的验证器进行验证.
When the object above is validated, each field is validated with the appropriate validator thanks to the "custom" attribute.
在我编写的 LinqToLucene 内容中,自定义属性非常好,因为它们允许您在运行时(通过反射)查找特定字段.例如,如果您有一个客户对象,您可能有兴趣获取所有已标记为索引我"的属性:自定义属性让您可以轻松完成此操作,因为它以一种方式公开有关该对象的元数据:查询方便.
In the LinqToLucene stuff I've written custom attributes are nice because they allow you to find (through reflection) specific fields at run time. For example, if you have a customer object, you may be interested in getting all the properties that have been marked as "index me": a custom attribute lets you do this easily since it exposes meta-data about the object in a manner that is easy to query.
这篇关于自定义 .NET 属性的实际使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!