【问题标题】:extending classes that must be used in an interface扩展必须在接口中使用的类
【发布时间】:2011-08-13 12:34:05
【问题描述】:

我创建了一个如下所示的界面。 DTO 对象是一个具有 3 个参数的复杂值对象。

public interface IOperation
{
    DTO Operate(DTO ArchiveAndPurgeDTO);
}

我需要实现此接口的人能够从原始 Value 对象继承并在需要时对其进行扩展。

我的假设是他们可以简单地继承 DTO 对象,添加(例如)另一个属性并在实现此接口的同一个类中使用它。

当我尝试使用扩展值对象时,Visual Studio 抱怨我不再隐含接口。

我怎样才能实现这个功能。

提前感谢您的任何想法和/或建议。

工程师

编辑: DTO 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Company.ArchiveAndPurge
{
    public class DTO
    {
        public DTO(String FriendlyID)
        {
            friendlyId = FriendlyID;
        }

        private String friendlyId = String.Empty;

        public String FriendlyId 
        { 
            get { return friendlyId; }
            set { friendlyId = value; } 
        }

        private String internalId = String.Empty;

        public String InternalyId
        {
            get { return internalId; }
            set { internalId = value; }
        }

        private Boolean archivedSuccessfully = false;

        public Boolean ArchivedSuccessfully
        {
            get { return archivedSuccessfully; }
            set { archivedSuccessfully = value; }
        }
    }
}

扩展 DTO:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Company.MSO.ArchiveAndPurge
{
    public class DTO: Company.ArchiveAndPurge.DTO
    {
        private Boolean requiresArchiving = true;

        public Boolean RequiresArchiving
        {
            get { return requiresArchiving; }
            set { requiresArchiving = value; }
        }
    }
}

VS抱怨的接口实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Company.ArchiveAndPurge.Contracts;
using Company.ArchiveAndPurge;

namespace Company.MSO.ArchiveAndPurge
{
    public class ResolveFriendlyId: IOperation
    {
        #region IOperation Members

        public DTO Operate(DTO ArchiveAndPurgeDTO)
        {
            ArchiveAndPurgeDTO.InternalyId = ArchiveAndPurgeDTO.FriendlyId;
            return ArchiveAndPurgeDTO;
        }

        #endregion
    }
}

【问题讨论】:

  • 显示DTO类代码和VS报错的代码

标签: c# oop inheritance interface


【解决方案1】:

据我了解,您可能有类似的情况:

public class ExtendedOperation : IOperation
{
    public ExtendedDTO Operate(ExtendedDTO dto)
    {
        ...
    }
}

这在两种情况下不起作用:

  • 实现接口方法时不能更改返回类型
  • 实现接口时不能更改参数列表

特别是,您不会以与以下代码兼容的方式实现IOperation

IOperation operation = new ExtendedOperation();
operation.Operate(new DTO());

我怀疑你可能想让界面通用:

public interface IOperation<T> where T : DTO
{
    T Operate(T dto);
}

【讨论】:

  • 与往常一样,Jon Skeet 更快。 ;)
【解决方案2】:

使用泛型:

public interface IOperation<T> where T : DTO
{
    T Operate(T ArchiveAndPurgeDTO);
}

【讨论】:

    猜你喜欢
    • 2014-01-02
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多