4

我们希望在属于类库的类中对接口进行“部分显式实现”。部分显式实现是指隐式实现接口的某些成员,显式实现同一接口的其余成员。请让我们知道我们需要注意的可能问题。

更具体地说,假设我们有IDriver如下定义的接口。该IDriver接口定义了所有驱动程序的基本功能。

interface IDriver
{
    IDriverIdentity DriverIdentity { get; }
    IDriverOperation Operation { get; }
    IDriverUtility Utility { get; }
}

public class MyDriver1 : IDriver
{
    // Implement the first and second member of IDriver implicitly
    public IDriverIdentity DriverIdentity
    {
        get
        {
            // return a IDriverIdentity object that user can use to assess Identity operations...
        }
    }
    public IDriverOperation Operation
    {
        get
        {
            // return a IDriverOperation object that user can use to access DriverOperation related properties and members..
        }
    }
    // Implement the last member of interface explicitly
    IDriverUtility IDriver.Utility
    {
        get
        {
            // return a IDriverUtility object that user can use to access fundamental utility operations that is mandated for every "Driver" object...
        }
    }
    public MyDriver1Utility Utility
    {
        get
        {
            // return MyDriver1Utility object that user can use to access utility operations available in this driver ...
        }
    }
}

同样让我们假设我们有MyDriver2,MyDriver3等隐式和显式地实现DriverIdentityand 。OperationUtility

在所有Driver类中,我们都希望隐式实现DriverIdentityOperation 以便用户在使用不同对象DriverIdentity时具有一致的视图。但是,我们希望显式实现该成员,并在从驱动程序对象访问时提供特定于该驱动程序的附加实用程序操作。OperationDriverUtility

我们希望了解在这种情况下部分显式实现的任何可能的副作用/后果。请让我们知道您的意见。

提前致谢!!

4

2 回答 2

1

确定需要接口?抽象类怎么样(因为我认为在您的情况下,驱动程序更像是“类型”而不是“行为”)。

public abstract class Driver
{
    public abstract DriverIdentity Identity { get; }
    public abstract DriverOperation Operation { get; }

    protected abstract DriverUtility Utility { get; }
}

如果您打算从类外部访问“实用程序”,那么您可以添加“内部”访问修饰符(但在这种情况下,您真的应该考虑将其声明为“公共”)。

于 2013-01-24T12:49:33.423 回答
1

也许你应该使用泛型,比如

interface IDriver<TUtillity> where TUtillity : IDriverUtility
{
  IDriverIdentity DriverIdentity { get; }
  IDriverOperation Operation { get; }
  TUtillity Utility { get; }
}

您还可以考虑使接口协变in TUtillity,即在声明中放置一个“out”:interface IDriver<out TUtillity>

于 2013-01-24T12:49:52.740 回答