use*_*988 2 c# constructor properties
我正在学习Java,最近我也开始学习C#.在Java中,我被告知要使用检查来编写类的某个成员的set方法,例如它是否为String - 字符串不为null.然后我们在构造函数中调用set方法,当我使用构造函数初始化类的对象时,它会验证我的数据.
所以在C#中有所谓的属性,这些属性应该与Java中的set/get方法相同,我可以在属性中验证我的数据.
如何在C#中的构造函数中调用set method/set属性,这样我就不必两次编写验证代码 - 一次在属性中,一次在构造函数中?
代码:类的一些简单示例
class Program
{
private int someVariable;
public Program(int someVariable)
{
this.someVariable = someVariable;
}
public int SomeVariable
{
get { return someVariable; }
set
{
if (value > 5)
{
Console.WriteLine("Error");
}
else
{
someVariable = value;
}
}
}
static void Main(string[] args)
{
Program pr = new Program(10);
pr.SomeVariable = 10;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以调用this.SomeVariable构造函数,然后执行set属性的一部分并验证值.现在,您通过直接设置变量someVariable值(有时称为"支持字段")来绕过此
通常在C#中,我将支持字段和属性保持在一起,以便更容易读取代码,如下所示:
int _someVariable;
public int SomeVariable
{
get { return _someVariable; }
set { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)
您可以从构造函数访问该属性:
public Program(int someVariable)
{
SomeVariable = someVariable;
}
Run Code Online (Sandbox Code Playgroud)
注意:您可能不应该直接在 setter 中写入控制台。一个更好的方法是抛出一个异常——这样你的程序的其余部分就可以做些什么了。或者,如果传入的值超出范围,您可以只设置一个默认值。
public int SomeVariable
{
get { return someVariable; }
set
{
if(value > 5)
throw new InvalidOperationException("SomeVariable cannot be greater than 5.");
someVariable = value;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,
public int SomeVariable
{
get { return someVariable; }
set
{
someVariable = value > 5 ? 5 : value;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2159 次 |
| 最近记录: |