本文介绍了C#从另一个的主体调用一个构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从另一个构造函数中调用另一个构造函数,该怎么做?
基本上
class foo {
public foo(int x,int y)
{
}
public foo )
{
// ... do something
//调用另一个构造函数
this(x,y); //不工作
foo(x,y); // not
}
}
解决方案
您必须找到一种链接构造函数的方法,如:
public foo(int x,int y){}
public foo(string s):this(XFromString(s),YFromString }
或将建筑代码移动到常用设置方法,例如:
public foo(int x,int y){Setup(x,y); }
public foo(string s)
{
// do stuff
int x = XFromString(s);
int y = YFromString(s);
Setup(x,y);
}
public void Setup(int x,int y){...}
I need to call one constructor from the body of another one, how to do that?
Basically
class foo {
public foo (int x, int y)
{
}
public foo (string s)
{
// ... do something
// call another constructor
this (x, y); // doesn't work
foo (x, y); // neither
}
}
解决方案
You can't.
You'll have to find a way to chain the constructors, as in:
public foo (int x, int y) { }
public foo (string s) : this(XFromString(s), YFromString(s)) { ... }
or move your construction code into a common setup method, like this:
public foo (int x, int y) { Setup(x, y); }
public foo (string s)
{
// do stuff
int x = XFromString(s);
int y = YFromString(s);
Setup(x, y);
}
public void Setup(int x, int y) { ... }
这篇关于C#从另一个的主体调用一个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!