我正在尝试验证是否可以转换抽象和接口类。我已经尝试了以下但是无法得到它,所以我认为我的方法不对。
答案 0 :(得分:0)
你的问题有点模糊。您的问题可能有很多种可能性。我试图在这里给他们。看看它是否符合您的需求。如果没有,请发表评论
建造班级结构
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
}
希望这有帮助