1

C# でジェネリック型を使用するメソッドを持つ基本クラスがあり、これらを継承する他のクラスがあります。親クラスで型を指定して、どこでも山かっこを避けたい...

これは、私の基本クラス クラス CBaseHome のサンプル メソッドです。

public List<T> fetchAll<T>(CBaseDb db, bool includeEmpty = true) where T : CBaseTable, new()
{
    List<T> retVal = new List<T>();
    ...
    return retVal;
}

このクラスから継承する親クラスがあります (この関数をオーバーライドせずに)

これを消費するクラスには、次のコードがあります...

List<student> students = new limxpoDB.Home.student().fetchAll<student>(db, false);

したがって、ここの Home.student クラスは CBaseHome クラスを継承し、student は CBaseTable を継承します...

Home.student クラスで、そのクラスの唯一の有効なジェネリック型が学生であることを言いたいので、消費するコードは次のようになります...

List<student> students = new limxpoDB.Home.student().fetchAll(db, false);

私はここで違いがわずかであることを理解していますが、私はこのライブラリをいくつかの VB>Net コードでも使用しています。

何か案は?

ありがとう

4

1 に答える 1

4

メソッドのジェネリック型パラメーターは、子クラスによって課すことはできません。だから私が持っている場合:

public class Parent {
    public List<T> GetStuff<T>() { ... }
}

できない:

public class Child : Parent {
    // This is not legal, and there is no legal equivalent.
    public List<ChildStuff> GetStuff<ChildStuff>() { ... }
}

できることは、メソッドではなく、親クラスをジェネリックにすることです。

public class Parent<T> {
    public List<T> GetStuff() { ... }
}

public class Child : Parent<ChildStuff> {
    // GetStuff for Child now automatically returns List<ChildStuff>
}
于 2012-05-09T20:59:30.953 に答える