在C#:初始化OBJ有/无默认值
public class SomeClass
{
int x;
int y;
SomeClass (int x, int y)
{
this.x = x;
this.y = y;
}
}
有没有简单的方法,使新的SomeClass的没有设置X和Y而是 对他们的默认值,如果我设定值,否则将它们设置有 默认值?
在C#:初始化OBJ有/无默认值
public class SomeClass
{
int x;
int y;
SomeClass (int x, int y)
{
this.x = x;
this.y = y;
}
}
有没有简单的方法,使新的SomeClass的没有设置X和Y而是 对他们的默认值,如果我设定值,否则将它们设置有 默认值?
当然,用C#6你可以用auto-implemented properties:
public class SomeClass
{
public int X { get; } = 123;
public int Y { get; } = 456;
public SomeClass(){ }
public SomeClass(int x, int y)
{
this.X = x;
this.Y = y;
}
}
当然,你需要一个参数的构造函数。
如果您指的是类型的默认值,则会自动完成(数字类型为0)。
您需要定义一个参数的构造函数:当你创建了一个对象
public class SomeClass
{
int x;
int y;
public SomeClass {}
public SomeClass (int x, int y)
{
this.x = x;
this.y = y;
}
}
:
var someClass = new SomeClass();
两个x
和y
将使用它们的默认值,这是0
如果你不想这样做,你可以通过传递给你已经声明了构造函数的构造函数来处理t值为x
和y
,正如David已经指出的那样。
默认的构造函数会自动执行该操作。 您可以在构造函数中使用可选参数。
Read more on named and optional parameters.
public class SomeClass
{
// You can also write this as
// public SomeClass(int x=default(int), int y=default(int)) if you do
// not want to hardcode default parameter value.
public SomeClass(int x=0, int y=0)
{
this.X = x;
this.Y = y;
}
}
你可以把它作为
void Main()
{
SomeClass a = new SomeClass();
SomeClass b = new SomeClass(1);
SomeClass c = new SomeClass(2,4);
}
当然...
new SomeClass(default(int), default(int))
或者更简单地说:
new SomeClass(0, 0)
int
的默认值始终为0
。所以,即使你有一个参数的构造函数定义它:
public SomeClass() { }
那些int
类成员仍默认为0
。
使用无参数的构造函数。
由于必须使用new
关键字以某种方式创建实例,因此可以在类中使用无参数构造函数。
public SomeClass()
{
x = 0;
y = 0;
}
建立一个无参数的构造函数? –
我有时需要设置值,有时不需要...... –
您可以在一个类中创建多个构造函数。 –