C#中:如果一个类有两个构造函数,什么是这些构造共享一些代码的最佳方式? [英] C#: if a class has two constructors, what is the best way for these constructors to share some code?

查看:193
本文介绍了C#中:如果一个类有两个构造函数,什么是这些构造共享一些代码的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#在VS2005:如果一个类有两个构造函数,什么是这些构造共享一些代码的最佳方式。



如。我怎么能避免在 X = 5 Y =在两个构造10 线以下内容:

 公共类为MyObject {

INT X;
INTÿ;
INT Z者除外;

公众为MyObject(){
X = 5;
Y = 10;
}

公共MyObject来(INT setZ){
X = 5;
Y = 10;
Z = setZ;
}


解决方案

刚刚链的共同构造...

 公开为MyObject(INT setZ)
:这()
{
Z = setZ;
}


C# in VS2005: if a class has two constructors, what is the best way for these constructors to share some code?

eg. How could I avoid having the x = 5 and y = 10 lines in both constructors for the following:

public class MyObject {

int x;
int y;
int z;

public MyObject() {
    x = 5;
    y = 10;
}

public MyObject(int setZ) {
    x = 5;
    y = 10;
    z = setZ;
}

解决方案

Just chain to the common constructor...

public MyObject(int setZ)
  : this()
{
  z = setZ;
}

这篇关于C#中:如果一个类有两个构造函数,什么是这些构造共享一些代码的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆