2010-08-24 222 views
2

这是一个相当初级的C#问题;我的道歉,但我一直无法在其他地方找到。C#类型转换为泛型参数

什么是从Object<class>转换为Object<interface>的最佳方法?

I.e.

//fake interface 
interface ignu {} 

//fake class which implements fake interface 
class bee : ignu {} 

//function which accepts a generic with the interface 
function bang(template<bee>) {} 

//template type but with a class that implements the interface 
template<bar> foo; 

//trying to call the function, but compiler complains it can't implicitly convert 
bang(foo); 

//compilers complains that it cannot convert from template<bee> to template<ignu> 
bang((template<ignu>)bee) 

也许我是远离基地,但这似乎应该工作和可行,但解决方案是逃避我。

编辑:mygen更改为模板,我用两指这是混淆

编辑同样的事情:我结束了使用强制类似于: 邦(bee.Cast());

+0

'mygen'应该是'template'吗? – recursive 2010-08-24 18:04:21

+0

我对bang的签名感到困惑,你是否试图说它接受一个任意的类? – MerickOWA 2010-08-24 18:10:57

回答

1

.NET 3.5在泛型中没有协变和协变性,如MonkeyWrench所示。但是,建立必要的铸造方法。

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<ccc> c = new List<ccc>(); 
     c.Add(new ccc()); 

     List<iii> i = new List<iii>(c.Cast<iii>()); 
    } 
} 

interface iii 
{ 
    void DoIt(); 
} 

class ccc : iii 
{ 
    public void DoIt() 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

我基本实现了chilltemp演示的功能。我赞赏Andorbal的建议和递归的第一个答案,他的评论说Cast将会避免使用lambda。 – William 2010-08-24 19:15:48

2

没有保证Generic<SubType>实际上可以作为Generic<BaseType>的替代品。

考虑一下:

List<int> intlist = new List<int>(); 
List<object> objlist = intlist; // compile error 
objlist.Add("foo"); // what should be in intlist now? 

你在找什么叫合作和禁忌变异。他们已被添加到C#4中。

+0

您正在发送双重讯息。你给的例子(与问题类似)在4.0中也不起作用。它不应该。 – 2010-08-24 18:13:28

+0

+1,为什么在泛型类型上没有自动协方差的很好的解释。 – Heinzi 2010-08-24 18:15:13

+0

您已经强调了面向对象编程中的继承问题;当涉及到接口时,这真的是一个有效的参数吗?接口的要点不是标准化您可能在同级类之间采取的某些操作?说我想在一个这样的类的集合而不是一个实例上做它真的不合理吗?这些都是诚实的问题,我从下面的答案中看到,我可以解决它,所以我正在寻找一些我应该注意的事项以及我应该注意的警告。 – William 2010-08-24 19:11:01

0

在.NET 3.5中,我会处理这样的事情在类似下面的列表:

list<bar> myList = new list<bar>; 
myList.Select<ignu>(x => x).ToList(); 

我认为这将不会太难为单个对象做这样的事情。

+0

如果使用.Cast而不是Select,则不需要传递一个lambda。 – recursive 2010-08-24 18:10:35

+0

这甚至更好! – Andorbal 2010-08-24 18:27:12