有什么办法可以完成List< object> list = new List< int>()in C#? [英] Is there any way to accomplish something like List<object> list = new List<int>() in C#?
问题描述
class A {}
class B extends A {}
public class Tests {
public static void main(String [] args){
ArrayList<延伸A> lists = new ArrayList< B>();
code $ <$ $ p
(其中 B扩展A
意味着B从A继承)
有没有可能?
谢谢
尽管C#4.0引入了接口方差的概念,但它不是(也不可能)专门做你所要求的。
在C#4.0中,您可以这样做:
IEnumerable<对象> foo = new List
编辑:正如Marc指出的那样,这不能通过值类型和引用类型来完成。然而,因为我认为你的问题更多的是关于一个广义的 A:B
而不是它是关于 int:object
,I认为重点在于。为了准确,我的意思是C#4.0会允许 这个元素:
IEnumerable< ;对象> foo = new List< string>();
但是你不能做你所描述的。也就是说,让我们考虑一下:
List< int> foo = new List< int>();
列表< object> bar = foo;
bar.Add(baz);
现在,当我们尝试访问 foo [0]
?你现在已经破坏了列表中的类型安全。
That is the question. What I want to accomplish is something similar to the following Java code:
class A { }
class B extends A { }
public class Tests {
public static void main(String [] args) {
ArrayList<? extends A> lists = new ArrayList<B>();
}
}
(in which B extends A
means B inherits from A)
Is it possible at all?
Thanks
No. While C# 4.0 introduces the concept of variance for interfaces, it isn't (and can't be) possible to do what you're asking specifically.
In C# 4.0, you can do this:
IEnumerable<object> foo = new List<int>();
Edit: As Marc points out, this can't be done with value types and reference Types. However, since I think your question was more about a generalized A:B
than it was about int:object
, I think the point carries. To be accurate, though, what I mean is that C# 4.0 will allow something this:
IEnumerable<object> foo = new List<string>();
But you can't do what you describe. Namely, let's consider:
List<int> foo = new List<int>();
List<object> bar = foo;
bar.Add("baz");
Now, what happens when we try to access foo[0]
? You've now broken the type safety on the list.
这篇关于有什么办法可以完成List< object> list = new List< int>()in C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!