This has been introduced in C# 4.0, but is there a way to achieve this in c# 3.0?
For e.g., consider the following code:
class Base
{
}
class Derived1 : Base
{
}
class Derived2 : Base
{
}
class User<T> where T : Base
{
}
class User1 : User<Derived1>
{
}
Now, I would like to have a list of User<T>, in which I can store User<Derived1> as well as User<Derived2>, but the following code fails to开发者_开发问答 compile in C# 3.0:
List<User<Base>> users = new List<User<Base>>();
users.Add(new User1());
Any ideas?
Not only is there no good workaround, but your code also won't work in C# 4.0 - only interfaces and delegates support variance, so you will never be able to treat a User<Derived> as a User<Base>.
The simplest approach is probably to use an ArrayList or List<object> and handle the casting yourself. There's no elegant way to do it in C# 3.
加载中,请稍侯......
精彩评论