2011-10-07 52 views
-1

简单的问题,我该如何解决这个问题?C#的构造函数调用

public MyClass(string s) 
{ 
    int k = s.Length; 
    int l = SomeFunction(s); 
    int m = GetNumber(); 
    if (Valid(l, m)) 
    { 
     int p = SomeOtherFunction(k, m); 
     MyBigObject o = new MyBigObject(p); 
     // here I want to call the other constructor MyClass(o) 
    } 
} 
public MyClass(MyBigObject x) 
{ 
    this.o = x; 
} 
+0

听起来像功课,我... – evilone

回答

2

提取通用的功能,并将其包装成一个单独的方法。

public MyClass(string s) 
{ 
    int k = s.Length; 
    int l = SomeFunction(s); 
    int m = GetNumber(); 
    if (Valid(l, m)) 
    { 
     int p = SomeOtherFunction(k, m); 
     MyBigObject o = new MyBigObject(p); 
     this.init(o); 
    } 
} 

public MyClass(MyBigObject x) 
{ 
    this.init(x); 
} 

public void init(MyBigObject x) 
{ 
    this.o = x; 
} 
+0

哇...我现在感觉傻了,反正,谢谢:) –

9

您可以用下面的代码做到这一点:

public MyClass(string s) : this(s.Length) 
{ 
} 
public MyClass(int x) 
{ 
    this.n = x; 
} 

为您编辑的问题:

public MyClass(string s) : this(ConstructorHelper(s)) 
{ 
} 
public MyClass(MyBigObject x) 
{ 
    this.o = x; 
} 

private static MyBigObject ConstructorHelper(string s) 
{ 
    int k = s.Length; 
    int l = SomeFunction(s); 
    int m = GetNumber(); 
    if (Valid(l, m)) 
    { 
     int p = SomeOtherFunction(k, m); 
     MyBigObject o = new MyBigObject(p); 
     return o; 
    } 

    return null; 
} 
+0

问题编辑 –

+0

感谢,另一个很好的答案,但我用扫罗的方法 –

0
public MyClass(string s) : this(s.Length) 
{ 
    // 
} 

public MyClass(int x) 
{ 
    this.n = x; 
} 
+0

问题编辑 –