.NET中的属性是什么? [英] What are attributes in .NET?

查看:110
本文介绍了.NET中的属性是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET中的属性是什么,它们有什么用,以及如何创建自己的属性?

What are attributes in .NET, what are they good for, and how do I create my own attributes?

推荐答案

元数据。有关您的对象/方法/属性的数据。

Metadata. Data about your objects/methods/properties.

例如,我可以声明一个名为:DisplayOrder的属性,这样我就可以轻松控制应在UI中显示的顺序。然后,我可以将其附加到类上并编写一些GUI组件,以提取属性并适当地对UI元素进行排序。

For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately.

public class DisplayWrapper
{
    private UnderlyingClass underlyingObject;

    public DisplayWrapper(UnderlyingClass u)
    {
        underlyingObject = u;
    }

    [DisplayOrder(1)]
    public int SomeInt
    {
        get
        {
            return underlyingObject .SomeInt;
        }
    }

    [DisplayOrder(2)]
    public DateTime SomeDate
    {
        get
        {
            return underlyingObject .SomeDate;
        }
    }
}

从而确保SomeInt始终在使用我的自定义GUI组件时显示在SomeDate之前。

Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components.

但是,您会看到它们在直接编码环境之外最常用。例如,Windows Designer广泛使用它们,因此它知道如何处理自定义对象。像这样使用BrowsableAttribute:

However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so:

[Browsable(false)]
public SomeCustomType DontShowThisInTheDesigner
{
    get{/*do something*/}
}

告诉设计师不要例如,在设计时将其列出在属性窗口中的可用属性中。

Tells the designer not to list this in the available properties in the Properties window at design time for example.

可以还将它们用于代码生成,编译操作(如Post-Sharp)或运行时操作(如Reflection.Emit)。
例如,您可以编写一些用于性能分析的代码,以透明方式包装代码所进行的每个调用并对其进行计时。您可以通过在特定方法上放置的属性来选择退出计时。

You could also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit. For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods.

public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args)
{
    bool time = true;
    foreach (Attribute a in target.GetCustomAttributes())
    {
        if (a.GetType() is NoTimingAttribute)
        {
            time = false;
            break;
        }
    }
    if (time)
    {
        StopWatch stopWatch = new StopWatch();
        stopWatch.Start();
        targetMethod.Invoke(target, args);
        stopWatch.Stop();
        HandleTimingOutput(targetMethod, stopWatch.Duration);
    }
    else
    {
        targetMethod.Invoke(target, args);
    }
}

声明它们很简单,只需创建一个继承的类来自属性。

Declaring them is easy, just make a class that inherits from Attribute.

public class DisplayOrderAttribute : Attribute
{
    private int order;

    public DisplayOrderAttribute(int order)
    {
        this.order = order;
    }

    public int Order
    {
        get { return order; }
    }
}

请记住,使用该属性时,您可以省略后缀 attribute,编译器会为您添加。

And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you.

注意:属性本身不会做任何事情-需要是其他一些使用它们的代码。有时已经为您编写了该代码,但有时您必须自己编写。例如,C#编译器关心某些框架,某些框架使用某些框架(例如,在加载程序集时,NUnit在类上查找[TestFixture],在测试方法上查找[Test])。

因此,在创建时您自己的自定义属性请注意,它根本不会影响代码的行为。您需要编写另一部分来检查属性(通过反射)并对其进行操作。

NOTE: Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly).
So when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them.

这篇关于.NET中的属性是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆