请帮助我理解以下内容:
public sealed class SqlConnection : DbConnection, ICloneable {...}
上节课我有两个疑问
在c中不可能有多重继承(我们可以通过接口实现)。但是这里dbconnection不是一个接口,那么它是如何支持多重继承的呢?
iclonable是一个接口。它有一个名为object clone()的方法。但是在sqlconnection类中,该方法没有实现。怎么可能?
请帮助我理解这一点
最佳答案
这里没有多重继承。您可以从一个类继承并实现多个接口。这里,DBConnection
是一个类,IClonable
是一个interface
iclonable声明为Explicit Interface
,这意味着您不能直接从类实例访问它,但必须显式转换为接口类型
例子
interface IDimensions
{
float Length();
float Width();
}
class Box : IDimensions
{
float lengthInches;
float widthInches;
public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicit interface member implementation:
float IDimensions.Length()
{
return lengthInches;
}
// Explicit interface member implementation:
float IDimensions.Width()
{
return widthInches;
}
public static void Main()
{
// Declare a class instance "myBox":
Box myBox = new Box(30.0f, 20.0f);
// Declare an interface instance "myDimensions":
IDimensions myDimensions = (IDimensions) myBox;
// Print out the dimensions of the box:
/* The following commented lines would produce compilation
errors because they try to access an explicitly implemented
interface member from a class instance: */
//System.Console.WriteLine("Length: {0}", myBox.Length());
//System.Console.WriteLine("Width: {0}", myBox.Width());
/* Print out the dimensions of the box by calling the methods
from an instance of the interface: */
System.Console.WriteLine("Length: {0}", myDimensions.Length());
System.Console.WriteLine("Width: {0}", myDimensions.Width());
}
}