在我的课上我有私有变量,我只在get/set中使用它.有时我会忘记,我不应该直接使用变量(即使在类中)也必须使用get/set.
如何使用变量的唯一方法是get/set?
public class A {
int x;
public XVariable {
get { return x; }
set { x = value }
// some additional operations
}
void SomeMethod() {
x = 5; // no
XVariable = 5; // yes
}
}
Run Code Online (Sandbox Code Playgroud)
C#具有自动属性.代码中不需要支持字段.
public class A {
public XVariable {
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用不同的访问修饰符.就像你只想在课堂上设置它一样.
public class A {
public XVariable {
get;
private set;
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码中不会有可以访问的支持字段,但编译器将在MSIL中生成一个(C#编译为).你不必担心那个部分.
一个潜在的缺点乔指出了自动道具,有时你需要在你设置的东西时在你的财产中执行其他动作(尤其是事件处理程序).但这对汽车道具来说是不可能的.在那种情况下,他的回答会更合适.但如果这不是您的用例的问题,那么我的答案应该足够了.
您可以创建一个基类,并在派生类中完成所有实际工作:
public class SomeBaseClass {
private int _x;
public int X { get { return _x; } set { _x = value; } }
}
public class DerivedClass : SomeBaseClass {
void DoSomething() {
// Does not have access to _x
}
}
Run Code Online (Sandbox Code Playgroud)