C# 在这种情况下,如何摆脱沮丧情绪?
我已经为此伤了头。情况就是这样。我有两种属性相似的文档。一个位置需要高级(基本级别)属性(名称、日期),创建要发送到另一个系统的特定文档需要“行”。目前如何实施: 数据类:C# 在这种情况下,如何摆脱沮丧情绪?,c#,generics,inheritance,C#,Generics,Inheritance,我已经为此伤了头。情况就是这样。我有两种属性相似的文档。一个位置需要高级(基本级别)属性(名称、日期),创建要发送到另一个系统的特定文档需要“行”。目前如何实施: 数据类: public abstract class BaseDocument { public string Name { get; set; } public DateTime Date { get; set; } } public abstract class B
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; }
}
我知道向下投射是不好的。但我不知道如何改变它。
我可以用泛型参数创建基类,但这样我就失去了只处理基类属性的能力。这将需要重写返回列表的类。
解决这个问题的办法是什么?需要解决吗?您可能需要使用接口
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;
}
}
}
公共接口IBaseDocument
{
字符串名称{get;set;}
日期时间日期{get;set;}
}
公共接口IDocumentWithRows
{
列出行{get;set;}
}
公共类文档类型一:IBaseDocument,IDocumentWithRows
{
字符串IBaseDocument.Name{get;set;}
DateTime IBaseDocument.Date{get;set;}
列出IDocumentWithRows.Rows{get;set;}
}
公共类文档处理器
{
公共作废处理文件(IBaseDocument文件)
{
开关(doc)
{
案例文档类型一文档类型一:
ProcessDocumentTypeOne(docTypeOne);
打破
案例文档类型二文档类型二:
ProcessDocumentTypeTwo(docTypeTwo);
打破
}
}
}
你想得到什么?请你解释一下,你的代码有什么问题吗?@PavelAnikhouski这是关于向下播放的。我觉得它看起来很难闻,好像有难闻的气味。但它是有效的,我认为没有其他方法可以让它变得更好。”我认为有些事情不会让人失望。但我不明白怎么做。
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;
}
}
}