我已经伤到头了。现在的情况是这样的。我有两种具有相似属性的文档。一个地方需要高级(基本级别)属性(名称、日期),“行”是创建发送到另一个系统的特定文档所必需的。它现在是如何实现的:
数据类:
public abstract class BaseDocument
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
public abstract class BaseDocument<TRowType> : BaseDocument
{
public abstract List<TRowType> Rows { get; set; }
}
public class DocumentTypeOne : BaseDocument<RowTypeOne>
{
public override List<RowTypeOne> Rows { get; set; }
}
public class DocumentTypeTwo : BaseDocument<RowTypeTwo>
{
public override List<RowTypeTwo> Rows { get; set; }
}
public class RowTypeOne
{
public int Cost { get; set; }
}
public class RowTypeTwo
{
public int Change { get; set; }
} ProcessorClass:
public class DocumentsProcessor
{
public void ProcessDocument(BaseDocument doc)
{
switch (doc)
{
case DocumentTypeOne t1:
ProcessDocumentTypeOne((DocumentTypeOne)doc);
break;
case DocumentTypeTwo t2:
ProcessDocumentsTypeTwo((DocumentTypeTwo)doc);
break;
default:
throw new ArgumentException($"Unhandled type {nameof(doc)}");
}
}
public void ProcessDocumentTypeOne(DocumentTypeOne docOne)
{
// specific actions
}
public void ProcessDocumentsTypeTwo(DocumentTypeTwo docTwo)
{
// other specific actions
}
}我知道向下传播不是件好事。但我不知道如何改变它。我可以用泛型参数来创建基类,但是那样我就不能只使用基本级别的属性了。这将需要重写返回列表的类。解决这个问题的方法是什么?它需要被解决吗?
发布于 2020-01-10 12:13:38
您可能想要使用接口。
public interface IBaseDocument
{
string Name { get; set; }
DateTime Date { get; set; }
}
public interface IDocumentWithRows<T>
{
List<T> Rows { get; set; }
}
public class DocumentTypeOne: IBaseDocument, IDocumentWithRows<RowTypeOne>
{
string IBaseDocument.Name { get; set; }
DateTime IBaseDocument.Date { get; set; }
List<RowTypeOne> IDocumentWithRows<RowTypeOne>.Rows { get; set; }
}
public class DocumentProcessor
{
public void ProcessDocument(IBaseDocument doc)
{
switch (doc)
{
case DocumentTypeOne docTypeOne:
ProcessDocumentTypeOne(docTypeOne);
break;
case DocumentTypeTwo docTypeTwo:
ProcessDocumentTypeTwo(docTypeTwo);
break;
}
}
}https://stackoverflow.com/questions/59675282
复制相似问题