Using a collection to store generics whose type implement a common interface
I have a type:
ExcelSheet<T>
And I have Some types that implement an interface:
IAddress
public class Instructor : IAddress
public class Student : IAddress
I would like to do the following.
....
ExcelSheet<Instructor> instructorSheet = GetSheet<Instructor>();
ExcelSheet<Student> student = GetSheet<Student>();
List<ExcelSheet<IAddress>> sheetsWithAddress = new List<ExcelSheet<IAddress>>
{
instructorSheet,
student
}
As written this is no开发者_开发知识库t possible. I'm using c# 4.0 Is there a way for this to work?
Is this a bad idea?Yes, you can! This is covariance and it's a new feature in C# 4.0.
Read more here:
- http://msdn.microsoft.com/en-us/library/dd799517.aspx
If you constrain the T in ExcelSheet to IAddress it will work.
class ExcelSheet<T> where T : IAddress
精彩评论