2017-10-11 121 views
0

在C#:初始化OBJ有/无默认值

public class SomeClass 
{ 
    int x; 
    int y; 
SomeClass (int x, int y) 
{ 
    this.x = x; 
    this.y = y; 
} 
} 

有没有简单的方法,使新的SomeClass的没有设置X和Y而是 对他们的默认值,如果我设定值,否则将它们设置有 默认值?

+0

建立一个无参数的构造函数? –

+0

我有时需要设置值,有时不需要...... –

+1

您可以在一个类中创建多个构造函数。 –

回答

4

当然,用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)。

1

您需要定义一个参数的构造函数:当你创建了一个对象

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(); 

两个xy将使用它们的默认值,这是0

初始化

如果你不想这样做,你可以通过传递给你已经声明了构造函数的构造函数来处理t值为xy,正如David已经指出的那样。

0

默认的构造函数会自动执行该操作。 您可以在构造函数中使用可选参数。

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); 

} 
2

当然...

new SomeClass(default(int), default(int)) 

或者更简单地说:

new SomeClass(0, 0) 

int的默认值始终为0。所以,即使你有一个参数的构造函数定义它:

public SomeClass() { } 

那些int类成员仍默认为0

0

使用无参数的构造函数。

由于必须使用new关键字以某种方式创建实例,因此可以在类中使用无参数构造函数。

public SomeClass() 
{ 
    x = 0; 
    y = 0; 
}