2011-10-07 77 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

問題編輯 –