Inherited classes as function parameter
I've got 2 classes (MyClass1 and MyClass2) that both inherit from MyBaseClass.
I want to write a开发者_开发技巧 function that takes a List of either of these as a parameter, like this
private void DoStuff(List<MyBaseClass> input)
{
...
}
How do I pass a List to this function?
You can't do it quite like that, as a List<MyClass1>
isn't a List<MyBaseClass>
. Search on Stack Overflow for generic variance for explanations of why that's the case.
One thing you can do is make it generic:
private void DoStuff<T>(List<T> input) where T : MyBaseClass
Alternatively, in C# 4 and .NET 4, if you only need to iterate over it, you could use IEnumerable<T>
which is covariant in T
:
private void DoStuff(IEnumerable<MyBaseClass> input)
精彩评论