我可以转换抽象类和接口类吗(如果我可以,将如何转换)
本文关键字:我可以 转换 何转换 如果 接口 抽象类 | 更新日期: 2023-09-27 17:58:24
我正在尝试验证是否可以转换抽象类和接口类。我试过以下几种,但都做不到,所以我认为我做得不对。
您的问题有点含糊。你的问题可能有很多可能性。我试着把它们送给这里。看看它是否符合你的需求。如果没有,请评论
构建类结构
public abstract class MyAbClass
{
public abstract void MyM1();
}
public interface IMyInterface
{
void MyM2();
}
public class MyConcretClass1 : MyAbClass
{
public override void MyM1()
{
//Your implementation here
}
}
public class MyConcretClass2 : IMyInterface
{
public void MyM2()
{
//Your implementation here
}
}
可能性
//Following are the possibilities
//This can be done in some other class and passed to some other method
//maybe a factory pattern
MyAbClass cls1 = new MyConcretClass1();
//Will call method of MyConcretClass1
cls1.MyM1();
if (cls1 is MyConcretClass1)
{
//Do casting here
}
var cls2 = cls1 as MyConcretClass1;
if (cls2 != null)
{
//Do your stuff here
}
//This can be done in some other class and passed to some other method
//maybe a factory pattern
IMyInterface cls3 = new MyConcretClass2();
//Will call method of MyConcretClass2
cls3.MyM2();
if (cls3 is MyConcretClass2)
{
//Do casting here
}
var cls4 = cls3 as MyConcretClass2;
if (cls4 != null)
{
//Do your stuff here
}
希望这能帮助