2013-06-21 134 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的代码中的一件神器 –

相关问题