public sealed class SqlConnection:DbConnection,ICloneable

时间:2014-05-24 10:14:23

标签: c# .net oop multiple-inheritance sqlconnection

请帮助我理解以下内容:

public sealed class SqlConnection : DbConnection, ICloneable {...}

在上面的课程中我有两个疑问

  1. 在C#中,多重继承是不可能的(我们可以通过接口来实现)。但是这里DBconnection不是一个接口,那么它如何支持多重继承?

  2. Iclonable是一个接口。它有一个名为object Clone()的方法。但是在Sqlconnection Class中没有实现该方法。怎么可能?

  3. 请帮我理解这个

2 个答案:

答案 0 :(得分:5)

  1. 这里没有多重遗产。您可以从一个类继承并实现多个接口。在此处,DBConnection是一个类,IClonableinterface

  2. IClonable声明为Explicit Interface,这意味着您无法直接从类实例访问它,但必须显式转换为接口类型

  3. 示例

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

答案 1 :(得分:1)

这不是多重继承。正如您所注意到的,DbConnection是一个类,ICloneable是一个接口。只有一个基类DbConnection,所以这是单继承。

至于Clone()方法,SqlConnection确实实现了它,但使用了explicit interface implementation。这会隐藏Clone()方法,直到您将SqlConnection对象视为ICloneable。当类的作者决定该类应该实现一个接口时,类可以这样做,但是该接口提供的方法通常不适合调用这个特定的类。