2013-04-21 79 views
2

我在基類中有一個方法,它應該返回類型爲derivation類型的自實例。例如:如何從基類型中聲明的方法返回派生類型

class A 
{ 
    public string X { get; set; } 

    public A SetX(string x) 
    { 
     this.X = x; 
     return this; 
    } 
} 

class B:A 
{ 
    public string Y { get; set; } 

    public B SetY(string y) 
    { 
     this.Y = y; 
     return this; 
    } 
} 

然後我想,如下流利調用方法:

B b = new B(); 

b.SetX("x") 
.SetY("y"); 

但這裏SetX回報A型,和A has'nt命名SetY任何方法。我如何設計這樣的功能?

+4

http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern – SLaks 2013-04-21 02:12:11

回答

3

有是可以做到這一點的兩件不同的事情。

第一種是使用泛型,使用類型參數來指定實際類型實例的:使用new關鍵字

public class A<T> where T:A<T> 
{ 
    public string X { get; private set; } 

    public T SetX(string x) 
    { 
     X = x; 
     return (T) this; 
    } 
} 

public class B<T> : A<T> 
    where T : B<T> 
{ 
    public string Y { get; private set; } 

    public T SetY(string y) 
    { 
     Y = y; 
     return (T) this; 
    } 
} 

public class A : A<A> 
{ 
} 

public class B : B<B> 
{ 
} 

第二是,在你B類,隱藏的方法,從A ,像這樣:

class A 
{ 
    public string X { get; set; } 

    public A SetX(string x) 
    { 
     this.X = x; 
     return this; 
    } 
} 

class B : A 
{ 
    public string Y { get; set; } 

    public new B SetX(string x) 
    { 
     return (B) base.SetX(x); 
    } 

    public B SetY(string y) 
    { 
     this.Y = y; 
     return this; 
    } 
} 
+0

第一種選擇是我已經知道的,第二種選擇是我所要求的。我認爲你應該重新排列選項來說清楚。 – 2013-04-21 07:48:43

+0

@HalilIbrahim我改變了你問的順序。很高興它有幫助 – mlorbetske 2013-04-21 17:16:45

0

使用保護:

protected string X { get; set; } 
protected A SetX(string x) 
{ 
    this.X = x; 
    return this; 
} 
4

一個辦法是宣佈SetX作爲一種通用的擴展方法:

public static T SetX<T>(this T a, string x) where T : A 
{ 
    a.X = x; 
    return a; 
} 

然後你可以這樣調用:

var newB = b.SetX("foo"); // returns type B 
+0

很酷的解決方案,但在我的研究中,A和B都是通用類,我無法在使用擴展方法時解析泛型類型參數。 – 2013-04-21 07:43:27

0

這一個爲我工作:

(b.SetX("1") as B).SetY("2"); 
相關問題