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;
}

现在我想知道我是否可以通过接口或抽象类进行一些继承,这样会给我各种类型的转换:

 (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);
4

2 回答 2

1

不太确定我是否理解您的问题,但是您是否想根据特定接口强制转换一个类?

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());

如果我有错误的想法,请原谅我,如果它不适合你,我会删除我的答案。

于 2013-10-01T10:13:07.927 回答
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界面中重叠。您可以使用显式接口实现来区分它们。

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;}
}
于 2013-10-01T10:15:33.033 回答