2013-10-01 94 views
1

我有基類A和子類。我正在尋找一種通過類的樹結構來構建某種類型的投射的方法。繼承類與子類和鑄造

class A 
{ 
    prop b; 
    prop c; 
    prop d; 
    prop E[] e; 
    prop F f; 
} 

class E 
{ 
    prop g; 
    prop h; 
    prop J j; 
} 

class J 
{ 
    prop k; 
} 

class F 
{ 
    prop l; 
} 

現在我想知道如果我能做到通過接口或抽象類繼承的一些會wchich給我各種各樣的種類蒙上這樣的:

(Cast1)A -> active props: c,d,E.g,E.J.k 
(Cast2)A -> active props: d,F.l 
(Cast3)A -> active props: b, E.h,E.g 

如何實現這一目標?我不需要經常使用每個類的屬性,所以這個投射對我來說很有用。

結果將是:

var f1 = a as Cast1; 
Console.WriteLine(f1.c); 
Console.WriteLine(f1.d); 
Console.WriteLine(f1.E[0].g); 
Console.WriteLine(f1.E[0].h);// this NOT 
Console.WriteLine(f1.E[0].J.k); 
Console.WriteLine(f1.E[1].g); 

var f2 = a as Cast2; 
Console.WriteLine(f2.d); 
Console.WriteLine(f2.F.l); 

var f3 = a as Cast3; 
Console.WriteLine(f3.b); 
Console.WriteLine(f3.E[0].h); 
Console.WriteLine(f3.E[1].h); 
Console.WriteLine(f3.E[2].h); 
Console.WriteLine(f3.E[2].g); 
+0

你打算做什麼,你的主動道具是什麼意思? –

+0

用'道具:c,d,E.g,E.J.k',帶有'道具:d,f.l'和接口'Cast3'的'Cast2',用'道具:b,E.h,E.g'創建界面'Cast1'。他們在你們班分別實施 –

+0

(Cast1)A。將顯示在屬性列表c,d,E中。 (Cast1)A.E。將顯示在屬性列表g,J.(Cast1)A.E.J。將顯示k。 – maszynaz

回答

1

不太清楚,如果我理解你的問題,但它像douns你想投的基於特定接口的類?

interface IFoo 
{ 
    void Hello1(); 
    void Hello2(); 
} 

interface IBar 
{ 
    void World1(); 
    void World2(); 
} 

class A1 : IFoo, IBar 
{ 
//..... 
} 

var a = new A1(); 

var f = a as IFoo; // Get IFoo methods. 

Console.WriteLine(f.Hello1()); 

var b = a as IBar; // Get IBar methods. 

Console.WriteLine(b.World2()); 

原諒我,如果我有錯誤的想法,我會刪除我的答案,如果它不適合你。

0

如果我明白你的問題,你想要什麼可以通過定義幾個接口來實現,並讓你的主類實現它們。

interface ICast1 
{ 
    prop c; 
    prop d; 
    E e; 
} 

interface ICast2 
{ 
    prop d; 
    F f; 
} 

class A : ICast1, ICast2 
{ 
    prop c; 
    prop d; 
    E e; 
    F f; 
} 

現在你可以轉換爲ICast1ICast2,只有得到你想要的意見。

雖然您的示例稍微複雜一點,但也會對E進行過濾。在這裏你需要更復雜的東西 - 有兩個不同的接口E,並且它們在你的接口ICast中重疊。您可以使用Explicit Interface Implementation來區分它們。

interface E1 
{ 
    prop g; 
    prop h; 
} 
interface E2 
{ 
    J j; 
} 
class E : E1, E2 
{ 
    prop g; prop h; J j; 
} 
interface ICast1 
{ 
    E1 e; 
} 
interface ICast2 
{ 
    E2 e; 
} 
class A : ICast1, ICast2 
{ 
    E1 ICast1.e {get;set;} 
    E2 ICast2.e {get;set;} 
}