-10

これが私がやりたいことです

クラスがあります

class A {}

別のクラスに関数があります

 class B
    {
        int count(object obj)
        {
                conn.table<T>.....   //what I want is conn.table<A>, how to do with obj as object passed to the function   
        }
    }

これが私がカウントを呼び出す方法です

B b = new B();
b.Count(a);  // where a is the object of class A

カウント関数でクラス名を渡したいのですが、そうするとobj.getType()エラーが発生します。

4

2 に答える 2

3

一般的な方法を使用します:

class B
{
    int count<T>(T obj) where T : A
    {
        // Here you can:
        // 1. Use obj as you would use any instance or derived instance of A.
        // 2. Pass T as a type param to other generic methods, 
        //    such as conn.table<T>(...)
    }
}
于 2013-06-21T15:01:55.287 に答える
1

今なら分かると思います。の型指定子を取得しようとしていますobj

私の実際の提案は、設計を再考するか、FishBasketGordo が言ったようなジェネリックを使用することです。

しかし、このようにしなければならない場合、私が知っている最善の方法は、obj が可能なさまざまなタイプを個別にチェックすることです

public int Count(object obj)
{
    if(obj is A)
    {
        conn.table<A>.....
    }
    else if(obj is B)
    {
        conn.table<B>.....
    }
    ...
}
于 2013-06-21T15:04:43.053 に答える