首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在这种情况下如何摆脱downcast?

在这种情况下如何摆脱downcast?
EN

Stack Overflow用户
提问于 2020-01-10 11:49:18
回答 1查看 31关注 0票数 0

我已经伤到头了。现在的情况是这样的。我有两种具有相似属性的文档。一个地方需要高级(基本级别)属性(名称、日期),“行”是创建发送到另一个系统的特定文档所必需的。它现在是如何实现的:

数据类:

代码语言:javascript
复制
    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:

代码语言:javascript
复制
    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
        }
    }

我知道向下传播不是件好事。但我不知道如何改变它。我可以用泛型参数来创建基类,但是那样我就不能只使用基本级别的属性了。这将需要重写返回列表的类。解决这个问题的方法是什么?它需要被解决吗?

EN

回答 1

Stack Overflow用户

发布于 2020-01-10 12:13:38

您可能想要使用接口。

代码语言:javascript
复制
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;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59675282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档