公共属性的默认值 [英] Default value for public properties

查看:62
本文介绍了公共属性的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某堂课上有公共财产.我想要此属性的默认值-1,而没有_MyField之类的私有变量(因为此类中的属性太多,因此我不会一一添加它们).

I have a public property in some class. I want a default value -1 for this property without an private variable like _MyField(because too many properties in this class, i won't add them one by one).

public int MyProperty { get; set; }

我认为

[DefaultValueAttribute]无法解决此问题.有任何想法吗?谢谢.

[DefaultValueAttribute] is not working for this issue i think. Any ideas? Thanks.

更新@ 2015年8月现在我们有了C#6!

UPDATE @ Aug 2015 Now we have C# 6!

public int MyProperty { get; set; } = 100;

public string EasyToUse { get; } = "YES!";

推荐答案

您基本上有两个选择-您可以在对象的构造函数中设置属性,也可以使用私有字段.

You basically have two options - you can set the property in the constructor of the object, or use a private field.

我个人认为,构造函数是最好的选择,因为人们很容易阅读您的代码,对于类的新实例您的意图是什么.

Personally, I feel the constructor is the best option, as it's clear to people reading your code what your intentions are for a fresh instance of your class.

[DefaultValue] 是用于可视设计器功能的属性,对您的类逻辑没有影响.

[DefaultValue] is an attribute meant for use with visual designer functionality, and has no effect on your class logic.

这篇关于公共属性的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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