简体   繁体   English

C#中的班级成员

[英]The class members in C#

What is the best practice in C# for class members with default non-zero values? 对于具有默认非零值的类成员,C#的最佳实践是什么?

You can write it this way: 您可以这样写:

private int someField = 9;
public int SomeField
{
   get ( return someField; }
   set { someField = value; }
}

Or this way: 或者这样:

public Int32 SomeField = 9;

But Int32 is identical to int. 但是Int32与int相同。

So, which way is better and may cause less problems? 那么,哪种方法更好,并且可以减少问题的发生?

Just use the C# aliases, they are shorter to read and are there for that reason. 只需使用C#别名,它们就更短了,因此存在。

You should not expose fields as public - you are breaking encapsulation this way. 您不应将字段public -这样会破坏封装。

In short, use: 简而言之,使用:

private int someField = 9;
public int SomeField
{
   get ( return someField; }
   set { someField = value; }
}

Alternative to the answer proposed by @Oded: @Oded提出的答案的替代方案:

public int field1 { get; set; } //auto-implemented property, :)

public MyClass() {
    field1 = 9; //or other default value
}

Also note that if you have multiple constructors, don't explicitly initialize fields in their declaration. 还要注意,如果您有多个构造函数,请不要在其声明中显式初始化字段。 Because the compiler generates code to initialize those fields for each constructor. 因为编译器会生成代码来初始化每个构造函数的字段。 For that situation, use one base constructor which initializes your fields and having the other constructors call this base constructor. 在这种情况下,请使用一个基本构造函数初始化您的字段,然后让其他构造函数调用此基本构造函数。

int field1;
int field2;
int field3;

public MyClass()
{
  field1 = 12;
  field2 = 1;
  field3 = 5;
}
public MyClass(int SomeValue) : this()
{
   field1 = SomeValue;
}

public MyClass(int SomeValue, int SomeOtherValue) : this()
{ 

   field1 = SomeValue;
   field2 = SomeOtherValue;
}

As a best practice I would avoid hard coding values like this. 作为最佳实践,我将避免像这样硬编码值。 They can be really tricky to maintain later. 他们以后维护起来可能很棘手。 You best bet is to create an enumerated list in a centralized place and cast those to Integers. 最好的选择是在集中位置创建一个枚举列表,然后将其转换为Integers。 This allows for better control / maintenance moving forward. 这样可以更好地进行控制/维护。

public enum SomeFieldValue
        {
            ValueOne = 1,
            ValueTwo = 2,
            ValueThree = 3
        }

        public int MyDefaultSomeValue = (int) SomeFieldValue.ValueOne;

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

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