自定义 .NET 属性的实际使用

Real world use of custom .NET attributes(自定义 .NET 属性的实际使用)
本文介绍了自定义 .NET 属性的实际使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您在现实世界中将自定义 .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 属性的实际使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)