扩展必须在接口中使用的类

时间:2011-08-13 12:34:05

标签: c# oop inheritance interface

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

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

我需要那些暗示此接口能够从原始Value对象继承并在需要时扩展它的人。

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

当我尝试使用扩展值对象时,Visual Studio抱怨我不再诋毁界面。

如何实现此功能。

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

Gineer

修改 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 Complains的接口实现:

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
    }
}

2 个答案:

答案 0 :(得分:2)

据我了解,你可能有类似的东西:

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);
}

答案 1 :(得分:1)

使用泛型:

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