具有子类和强制转换的继承类
本文关键字:转换 继承 子类 | 更新日期: 2023-09-27 18:33:30
我有基类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);
不太确定我是否理解你的问题,但它就像你想基于特定接口投射一个类一样?
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());
如果我有错误的想法,请原谅我,如果不适合您,我会删除我的答案。
如果我理解你的问题,你想要的可以通过定义几个接口来实现,并让你的主类实现它们。
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;
}
现在,您可以投射到ICast1
或ICast2
,并仅获得所需的视图。
不过,您的示例有点复杂,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;}
}