简体   繁体   中英

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 not 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:

If you constrain the T in ExcelSheet to IAddress it will work.

class ExcelSheet<T> where T : IAddress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM