C# 属性属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/208703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# property attributes
提问by TK.
I have seen the following code:
我看到了以下代码:
[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{...}
The functionality from the above snippit seems clear enough, I have no idea as to how I can use it to do useful things. Im not even sure as to what name to give it!
上述代码段的功能似乎很清楚,我不知道如何使用它来做有用的事情。我什至不确定给它起什么名字!
Does anyone know where I can find more information/a tutorial on these property attributes? I would be also interested in any novel / useful tasks this feature can do.
有谁知道我在哪里可以找到有关这些属性属性的更多信息/教程?我也会对这个功能可以做的任何新颖/有用的任务感兴趣。
采纳答案by Marc Gravell
People have already covered the UI aspect - attributes have other uses, though... for example, they are used extensively in most serialization frameworks.
Some attributes are given special treatment by the compiler - for example, [PrincipalPermission(...)]
adds declarative security to a method, allowing you to (automatically) check that the user has suitable access.
人们已经涵盖了 UI 方面——尽管属性还有其他用途……例如,它们在大多数序列化框架中被广泛使用。编译器对某些属性进行了特殊处理 - 例如,[PrincipalPermission(...)]
向方法添加声明性安全性,允许您(自动)检查用户是否具有合适的访问权限。
To add your own special handling, you can use PostSharp; there are many great examples of using PostSharp to do AOP things, like logging - or just code simplification, such as with automatic INotifyPropertyChanged
implementation.
要添加您自己的特殊处理,您可以使用PostSharp;有很多很好的例子使用 PostSharp 来做 AOP 的事情,比如日志记录 - 或者只是代码简化,比如自动INotifyPropertyChanged
实现。
回答by Greg Dean
These attributes customize the design time experience.
这些属性定制了设计时体验。
回答by Isak Savo
The ones in your example is used by the visual designer (i.e. MS Expression Blend and Visual Studio designer) to give hints in the designer UI.
您示例中的那些由视觉设计器(即 MS Expression Blend 和 Visual Studio 设计器)用于在设计器 UI 中提供提示。
Note that they are metadata and will not affect the property logic. Setting DefaultValue
for instance will not set the property to that value by default, you have to do that manually.
请注意,它们是元数据,不会影响属性逻辑。设置DefaultValue
为实例不会将该属性设置为默认情况下该值,你必须这样做手工。
If you for some reason want to access these attributes, you would have to use reflection.
如果您出于某种原因想要访问这些属性,则必须使用反射。
See MSDNfor more information about designer attributes.
有关设计器属性的更多信息,请参阅MSDN。
回答by Grzenio
They are called Attributes, there is a lot of information in msdn, e.g. http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx
它们被称为属性,msdn 中有很多信息,例如http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx
In general they don't "do" anything on their own, they are used by some other code that will use your class. XmlSerialization is a good example: XmlSerializer (provided by Microsoft as part of the framework) can almost any class (there are a number of requirements on the class though) - it uses reflection to see what data is contained in the class. You can use attributes (defined together with XmlSerializer) to change the way XmlSerializer will serialize your class (e.g. tell it to save the data as attribute instead of an element).
一般来说,它们不会自己“做”任何事情,它们会被其他一些将使用您的类的代码使用。XmlSerialization 是一个很好的例子:XmlSerializer(由 Microsoft 作为框架的一部分提供)几乎可以用于任何类(尽管对类有很多要求)——它使用反射来查看类中包含哪些数据。您可以使用属性(与 XmlSerializer 一起定义)来更改 XmlSerializer 序列化您的类的方式(例如,告诉它将数据保存为属性而不是元素)。
回答by James Curran
The functionality from the above snippit seems clear enough,
以上代码段的功能似乎很清楚,
Maybe not, as many people think that [DefaultValue()] setsthe value of the property. Actually, all it does to tell some visual designer (e.g. Visual Studio), what the code is going to set the default value to. That way it knows to boldthe value in the Property Window if it's set to something else.
也许不是,因为很多人认为 [DefaultValue()]设置了属性的值。实际上,它所做的只是告诉一些可视化设计器(例如 Visual Studio),代码会将默认值设置为什么。这样它就知道如果将属性窗口中的值设置为其他值,则将其加粗。
回答by TimothyP
We use it to define which graphical designer should be loaded to configure an instance of a specific type.
我们使用它来定义应该加载哪个图形设计器来配置特定类型的实例。
That is to say, we have a kind of workflow designer which loads all possible command types from an assembly. These command types have properties that need to be configured, so every command type has the need for a different designer (usercontrol).
也就是说,我们有一种工作流设计器,可以从程序集中加载所有可能的命令类型。这些命令类型具有需要配置的属性,因此每种命令类型都需要不同的设计器(用户控件)。
For example, consider the following command type (called a composite in our solution)
例如,考虑以下命令类型(在我们的解决方案中称为复合)
[CompositeMetaData("Delay","Sets the delay between commands",1)]
[CompositeDesigner(typeof(DelayCompositeDesigner))]
public class DelayComposite : CompositeBase
{
// code here
}
This is information is used in two places
这是信息在两个地方使用
1) When the designer creates a list of commands, it uses the CompositeMetaData to display more information about the command.
1) 当设计器创建命令列表时,它使用 CompositeMetaData 来显示有关命令的更多信息。
2) When the user adds a command to the designer and the designer creates an instance of that class, it looks at the CompositeDesigner property, creates a new instance of the specified type (usercontrol) and adds it to the visual designer.
2) 当用户向设计器添加命令并且设计器创建该类的实例时,它会查看 CompositeDesigner 属性,创建指定类型(用户控件)的新实例并将其添加到可视设计器。
Consider the following code, we use to load the commands into our "toolbar":
考虑以下代码,我们用来将命令加载到我们的“工具栏”中:
foreach (Type t in assembly.GetExportedTypes())
{
Console.WriteLine(t.Name);
if (t.Name.EndsWith("Composite"))
{
var attributes = t.GetCustomAttributes(false);
ToolboxListItem item = new ToolboxListItem();
CompositeMetaDataAttribute meta = (CompositeMetaDataAttribute)attributes
.Where(a => a.GetType() == typeof(Vialis.LightLink.Attributes.CompositeMetaDataAttribute)).First();
item.Name = meta.DisplayName;
item.Description = meta.Description;
item.Length = meta.Length;
item.CompositType = t;
this.lstCommands.Items.Add(item);
}
}
As you can see, for every type in the assembly of which the name ends with "Composite", we get the custom attributes and use that information to populate our ToolboxListItem instance.
如您所见,对于程序集中名称以“Composite”结尾的每种类型,我们都会获取自定义属性并使用该信息来填充我们的 ToolboxListItem 实例。
As for loading the designer, the attribute is retreived like this:
至于加载设计器,属性是这样检索的:
var designerAttribute = (CompositeDesignerAttribute)item.CompositType.GetCustomAttributes(false)
.Where(a => a.GetType() == typeof(CompositeDesignerAttribute)).FirstOrDefault();
This is just one example of how you might be able to use custom attributes,
这只是您如何使用自定义属性的一个示例,
I hope this gives you a place to start.
我希望这能给你一个开始的地方。