接口类型方法参数实现
时间:2020-03-06 14:25:11 来源:igfitidea点击:
是否可以这样做:
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) { ... } }
解决方案
不,这是不可能的。方法应具有与接口中声明的签名相同的签名。
但是,我们可以使用类型参数约束:
interface IDBClass<T> where T:IDbCommand { void Test(T cmd); } class DBClass:IDBClass<SqlCommand> { public void Test(SqlCommand cmd) { } }
尝试编译它。如果DBBase
没有实现IDBBase
,编译器将报告一个错误。
不,不可能。我尝试编译此:
interface Interface1 { } class Class1 : Interface1 {} interface Interface2 { void Foo(Interface1 i1);} class Class2 : Interface2 {void Foo(Class1 c1) {}}
我得到了这个错误:
'Class2' does not implement interface member 'Interface2.Foo(Interface1)'
从C3.0开始,协方差和协方差不受广泛支持,除了将方法组分配给委托。我们可以使用私有接口实现来模拟它,并使用更具体的参数调用public方法:
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) { ... } }