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

1

本文介绍了自定义 .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 属性的实际使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14

具有未知类型的 CreateDelegate
CreateDelegate with unknown types(具有未知类型的 CreateDelegate)...
2023-11-11 C#/.NET开发问题
5

Func<T>.BeginInvoke 使用线程池吗?
Does Funclt;Tgt;.BeginInvoke use the ThreadPool?(Funclt;Tgt;.BeginInvoke 使用线程池吗?)...
2023-11-11 C#/.NET开发问题
6

如何为具有空目标的实例方法创建委托?
How to create a delegate to an instance method with a null target?(如何为具有空目标的实例方法创建委托?)...
2023-11-11 C#/.NET开发问题
6