2013-06-21 131 views
-9

這是我想要做的不能隱式轉換對象類型

我有一個類

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()我得到一個錯誤。

+0

「a」從哪裏來?它在哪裏立竿見影? –

+0

'obj.getType()'給你什麼錯誤?總是發佈任何錯誤的詳細信息... – Chris

+1

如果你的錯誤發生在'obj.getType()'爲什麼你沒有發佈你的代碼的一部分? –

回答

3

使用generic method

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>(...) 
    } 
} 
1

我想我現在明白了。你想獲得obj

我的實際建議的類型說明符會重新考慮你的設計和/或使用泛型像FishBasketGordo說,

,但如果你一定要做到這樣,最好的我知道的方式是單獨檢查obj可以是的不同類型

public int Count(object obj) 
{ 
    if(obj is A) 
    { 
     conn.table<A>..... 
    } 
    else if(obj is B) 
    { 
     conn.table<B>..... 
    } 
    ... 
} 
+0

@FishBasketGordo它也是OP的代碼中的一件神器 –

相關問題