请在代码中查看我的评论,我怎样才能获得具体的操作类型,为什么直接转换为 MyDto 不起作用?
public class Gen1Layer<TData, TAction> : GenBaseLayer<TData, TAction>
{
public Gen1Layer(IGenBaseLayer<TData, TAction> layer) : base(layer) { }
public override Document<TData, TAction> ProcessDocument(Document<TData, TAction> document)
{
// Does not work!
// MyDto dto = (MyDto) document.Data;
// Does cast!
MyDto dto1 = document.Data as MyDto;
// Does not work!
MyConsts.ActionType bla = document.ActionType as MyConsts.ActionType;
// Does not work!
MyConsts.ActionType bla = (MyConsts.ActionType)document.ActionType;
}
}
Gen1Layer 是这样调用的:
IGenBaseLayer<MyDto,MyConsts.ActionType> layer = new Gen1Layer<MyDto,MyConsts.ActionType>(null);
Document<MyDto,MyConsts.ActionType> doc = new Document<MyDto,MyConsts.ActionType>(new MyDto(),MyConsts.ActionType.Add,new Session());
doc = layer.ProcessDocument(doc);
public class Document<TData,TAction>
{
public Document(TData data, TAction actionType,Session session)
{
Data = data;
ActionType = actionType;
Session = session;
}
public TData Data { get; set; }
public TAction ActionType { get; set; }
public Session Session { get; set; }
}
public class MyConsts
{
public enum ActionType
{
Get,
Add,
}
}
public interface IGenBaseLayer<TData, TAction>
{
Document<TData,TAction> ProcessDocument(Document<TData,TAction> document);
}
public class GenBaseLayer<TData,TAction> : IGenBaseLayer<TData,TAction>
{
public GenBaseLayer(IGenBaseLayer<TData,TAction> layer)
{
NextLayer = layer;
}
public IGenBaseLayer<TData,TAction> NextLayer { get; set; }
public virtual Document<TData,TAction> ProcessDocument(Document<TData, TAction> document)
{
Console.Write("Gen’s");
return document;
}
}
我想要实现的是拥有一个通用的基础层,而派生层是覆盖的 ProcessDocument 方法中的具体类型。我知道这会破坏 IGenBaseLayer 永远不会调用派生层实例的 ProcessDocument 方法的多态性。但这就是我需要的。每个层都可以拥有具有不同封闭通用类型的文档,例如 CustomerDto 或 SupplierDto 以及相关的 CustomerActionType 或 SupplierActionType。