[英]C# OOP Cast interface parameter to concrete type
我正在尝试为应用程序中的某些基本流程构建一种框架。 在某些情况下,我必须执行一些操作,但是根据某些情况,这些操作是不同的。 我已经做了一些不确定的事情,做这样的事情我不确定:
public interface IMyDto
{
string makerIdentifier { get; set; }
}
public class DtoOne:IMyDto
{
public string makerIdentifier { get; set; }
//Custom properties for ConcreteOne
}
public class DtoTwo:IMyDto
{
public string makerIdentifier { get; set; }
//Custom properties for ConcreteTwo
}
public abstract class AbstractMaker
{
public abstract void DoSomething(IMyDto myInterface);
}
public class ConcreteMakerOne:AbstractMaker
{
public override void DoSomething(IMyDto myInterface)
{
var concrete = myInterface as DtoOne;
// If concrete is not null..do stuff with DtoOne properties
}
}
public class ConcreteMakerTwo : AbstractMaker
{
public override void DoSomething(IMyDto myInterface)
{
var concrete = myInterface as DtoTwo;
// If concrete is not null..do stuff with DtoTwo properties
}
}
public class Customer
{
public void MakeSomething(IMyDto myDto)
{
var maker = GetMaker();
maker.DoSomething(myDto);
}
private AbstractMaker GetMaker()
{
//Stuff to determine if return ConcreteOne or ConcreteTwo
}
}
我不满意的代码是:
var concrete = myInterface as DtoOne;
如果有人可以给我一些有关这种情况下的模式或良好实践的建议或技巧,我将不胜感激。
尚不清楚所有用例是什么,但其中一个选项可能是泛型:
public abstract class AbstractMaker<T> where T:IMyDto
{
public abstract void DoSomething(T myInterface);
}
public class ConcreteMakerTwo : AbstractMaker<DtoTwo>
{
public override void DoSomething(DtoTwo myInterface)
{
// now you are certain that myInterface is a DtoTwo
}
}
我不确定我是否正确理解您的要求,但是为什么不将DoSomething方法放入IMyDto并在DtoOne , DtoTwo等中以不同的方式实现呢? 只有一个Maker ,并且总是调用相同的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.