Generics Problem - C# 3.0
I have a problem:
class Base
{
}
class DerivedClass : B开发者_如何学Case
{
}
class Test<T> where T : Base
{
}
and something like so:
Test<Base> a = new Test<DerivedClass>();
I think there's a way around it in C# 4.0, but is there a way to do something like so in C# 3?
Short answer: No, there is no way.
Long answer: No, there is no way in neither C# 3.0 nor C# 4.0, because co- and contravariance is not supported in C# 3.0 at all and only on delegate types and interfaces in C# 4.0.
UPDATE:
If you want to save several instances of this class in a list, independent of the concrete type of T
, one workaround could look like this:
Create an interface ITest
that uses Base
everywhere you would use T
. Make Test<T>
implement that interface and hide the methods from ITest
by using explicit interface implementation. Use ITest
as parameter type to your method.
Sample code:
class Base
{
public int Info { get; set; }
}
class Derived : Base
{
public int Info2 { get; set; }
}
interface ITest
{
Base Data { get; set; }
}
class Test<T> : ITest
where T : Base
{
public T Data { get { return (T) (((ITest) this).Data); } set { ((ITest) this).Data = value; } }
Base ITest.Data { get; set; }
}
List<ITest> list = new List<ITest>();
list.Add(new Test<Base>());
list.Add(new Test<Derived>());
If you just want to pass that class to a method without requiring a specific T
, you can make your method generic as well:
void YourMethod<T>(Test<T> test) where T : Base
{
Console.WriteLine(test.Data.Info);
}
YourMethod(new Test<Base>());
YourMethod(new Test<Derived>());
That's covariance you want and there isn't much of a way round in C# 3.0, other than using casting.
A Test<DerivedClass>
does not inherit from a Test<Base>
even if DerivedClass
inherits from Base
.
精彩评论