简体   繁体   English

类模型-设置默认值

[英]Class model - setting default value

When defining the default value, what is the difference between 定义默认值时,两者之间有什么区别

[DefaultValue("member")]
public string Role { get; set; }

and

public string Role { get; set; } = "member";

The first is an attribute which can be useful for meta-programming. 第一个是可用于元编程的属性。 For example, you might want to remember what the default value is if someone clears an input. 例如,您可能想记住如果有人清除输入,则默认值是什么。 It has nothing to do with the C# language itself. 它与C#语言本身无关 It does not modify the value of Role . 它不会修改Role的值。

The second actually sets the property's value to 'member' in memory. 第二个实际上将属性的值设置为内存中的“成员”。

From the documentation : 文档中

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. DefaultValueAttribute不会导致成员使用该属性的值自动初始化。 You must set the initial value in your code. 您必须在代码中设置初始值。

In other words, your first example helps tools (like the Windows Forms Designer) to know what the intended default value for a property is. 换句话说,您的第一个示例可帮助工具(例如Windows Forms Designer)了解属性的预期默认值是什么。 But it does nothing at run-time. 但是在运行时它什么也做。

If you want a property to be assigned a default value at run-time, you have to do it yourself, as in the second example you show. 如果希望在运行时为属性分配默认值,则必须自己完成操作,如第二个示例所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM