【问题标题】:Interface type method parameter implementation接口类型方法参数实现
【发布时间】:2008-09-19 08:40:44
【问题描述】:

是否可以这样做:

interface IDBBase {
     DataTable getDataTableSql(DataTable curTable,IDbCommand cmd);
     ...
}

class DBBase : IDBBase {
     public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
         ...
     }
}

我想使用接口来实现 d/t 提供者(MS-SQL、Oracle...);其中有一些签名要在实现它的相应类中实现。我也试过这样:

genClass<typeOj>
{
    typeOj instOj;

    public  genClass(typeOj o)
    {      instOj=o;    }


    public typeOj getType()
    {        return instOj;    }

...

interface IDBBase 
{
    DataTable getDataTableSql(DataTable curTable,genClass<idcommand> cmd);
    ...
}

class DBBase : IDBBase 
{
    public DataTable getDataTableSql(DataTable curTable, genClass<SqlCommand> cmd)
    {
        ...
    }
}

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    Covariance and contravariance 从 C# 3.0 开始不受广泛支持,除了将方法组分配给委托。您可以通过使用私有接口实现并使用更具体的参数调用公共方法来模拟它:

    class DBBase : IDBBase {
    
        DataTable IDBBase.getDataTableSql(DataTable curTable, IDbCommand cmd) {
             return getDataTableSql(curTable, (SqlCommand)cmd); // of course you should do some type checks
         }
    
         public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
             ...
         }
    }
    

    【讨论】:

      【解决方案2】:

      不,这是不可能的。方法的签名应与接口中声明的签名相同。

      但是你可以使用类型参数约束:

      interface IDBClass<T> where T:IDbCommand
      {
          void Test(T cmd);
      }
      
      class DBClass:IDBClass<SqlCommand>
      {
          public void Test(SqlCommand cmd)
          {
          }
      }
      

      【讨论】:

        【解决方案3】:

        尝试编译它。如果DBBase没有实现IDBBase,编译器会报错。

        【讨论】:

          【解决方案4】:

          不,这是不可能的。我试着编译这个:

          interface Interface1 { }
          class Class1 : Interface1 {}
          
          interface Interface2 { void Foo(Interface1 i1);}
          class Class2 : Interface2 {void Foo(Class1 c1) {}}
          

          我得到了这个错误:

          'Class2' 没有实现接口成员'Interface2.Foo(Interface1)'

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-01-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-11
            相关资源
            最近更新 更多