我们希望在属于类库的类中对接口进行“部分显式实现”.通过部分显式实现,我的意思是隐式地实现接口的某些成员,并明确地实现相同接口的剩余成员.
请告诉我们可能需要注意的问题.
更具体地说,假设我们有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等,它们隐式地实现了DriverIdentity和Operation,并且显式地实现了Utility.
在所有Driver类中,我们希望隐式实现DriverIdentity和Operation,以便用户在使用不同的Driver对象时具有DriverIdentity和Operation的一致视图.
但是,我们希望显式实现Utility成员,并在从驱动程序对象访问时提供特定于该驱动程序的其他实用程序操作.
我们希望了解在这种情况下部分显式实现的任何可能的副作用/后果.请告诉我们您的意见.
提前致谢!!
最佳答案 当然你需要一个界面?抽象类怎么样(因为我认为在你的情况下驱动程序更像是“类型”而不是“行为”).
public abstract class Driver
{
public abstract DriverIdentity Identity { get; }
public abstract DriverOperation Operation { get; }
protected abstract DriverUtility Utility { get; }
}
如果您打算从类外部访问“实用程序”,那么您可以添加“内部”访问修饰符(但在这种情况下,您应该考虑将其声明为“公共”).