2008-09-19 24 views
2

は次のように行うことが可能です:インターフェイスの型メソッドのパラメータの実装

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) 
    { 
     ... 
    } 
} 
+0

質問は? –

答えて

3

ありません、それは不可能です。メソッドは、インタフェース内で宣言されたシグネチャと同じシグネチャを持つ必要があります。

しかし、あなたは型パラメータ制約を使用することができます。

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

class DBClass:IDBClass<SqlCommand> 
{ 
    public void Test(SqlCommand cmd) 
    { 
    } 
} 
1

はそれをコンパイルしてみます。 DBBaseIDBBaseが実装されていない場合、コンパイラはエラーを報告します。

1

いいえ、不可能です。私はこれをコンパイルしてみました:

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)'

3

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) { 
     ... 
    } 
} 
関連する問題