1)我对编程还很陌生,并且已经阅读了一些关于getter和setter的内容.但我真的不明白他们为什么被使用..任何人都可以解释它,或者指向一篇文章?(我读过的那些对我来说并不是真的可以理解......)
2)在我当前的项目中,我有一个类,我声明并初始化一个结构数组.我现在需要从另一个类访问该数组,但它给了我错误:An object reference is required to access non-static member 'BaseCharacter.Attributes'.
我想这可能意味着我需要使用getter和setter?但这对阵列有什么用呢?
提前致谢!
西蒙.
编辑:第二个问题得到解决,这带给我其他的东西.当我想在另一个类中使用某个类时,我正在创建该类的新实例,对吧?这意味着我得到了原始价值?但这不是我想要的.
第二个类用于生成UI,并且需要我在第一个类中保留的值.
在某些时候,我将实现保存文件(XML甚至在后期的服务器上).那么我可以从这些文件中获取值吗?
对于getter和setter(使用它们的东西称为Properties),它只是一种方便且美观的方式,可以让人们认为他们正在使用变量,但每当更新或访问变量时都要进行一些计算.例如:
BankAccount.Interest
Run Code Online (Sandbox Code Playgroud)
看起来比
BankAccount.GetInterest()
Run Code Online (Sandbox Code Playgroud)
即使您可以在两种情况下都要求计算利息.
它们还用于使变量能够从类外部访问,但只能使用此技术在类中进行更改:
public double Interest {
get;
private set;
}
Run Code Online (Sandbox Code Playgroud)
有关正在使用的setter的示例,如果您曾经使用过Windows Forms并更新了控件Height或Width属性,那么您正在使用setter.虽然看起来你正在使用一个普通的实例变量c.Height = 400,但你真的要c通过在一个新的地方重新绘制来更新它的位置.因此,setter会在变量发生变化时通知您,因此您的类可以根据新值更新其他内容.
另一个属性的应用是,您可以检查人们尝试将属性设置为的值.例如,如果您想维持每个银行帐户的利率,但又不想允许负数或数字超过50,那么您只需使用一个setter:
private int _interestRate = someDefault;
public int InterestRate {
get { return _interestRate; }
set {
if (value < 0 || value > 50)
throw new SomeException(); // or just don't update _interestRate
_interestRate = value;
}
}
Run Code Online (Sandbox Code Playgroud)
这样人们就无法将公共值设置为无效值.
一:你可以成为那个成员static.这意味着只有其中一个存在于整个类而不是每个类的一个实例.然后你可以访问它ClassName.MemberName.
你可以这样做:
// inside the BaseCharacter class definition:
public static SomeStruct[] Attributes = new SomeStruct[size];
// then to use it somewhere else in your code, do something with
BaseCharacter.Attributes[index]
Run Code Online (Sandbox Code Playgroud)
二:你必须创建一个类的实例并通过它访问该数组.这意味着每个对象都有自己的单独数组.
你这样做是这样的:
BaseCharacter bc = new BaseCharacter();
// use bc.Attributes
Run Code Online (Sandbox Code Playgroud)
第二个可能是你想要做的,因为你可能想要从所有其他角色中单独修改每个角色的属性.