公共属性的默认值

编程入门 行业动态 更新时间:2024-10-21 18:44:35
本文介绍了公共属性的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在某堂课上有公共财产.我想要此属性的默认值-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.

更多推荐

公共属性的默认值

本文发布于:2023-11-14 00:10:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!