2013-10-01 96 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;} 
}