C#: Declaring and using a list of generic classes with different types, how?

后端 未结 9 1509
猫巷女王i
猫巷女王i 2020-12-23 21:19

Having the following generic class that would contain either string, int, float, long as the type:

public class MyData         


        
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 21:51

    You can't do it the way you want.

    When an instance of a generic class is initialized, it is bound to particular type. Since you want to hold objects of different types in your list, you have to create an instance bound to the least common denominator — in your case it's Object.

    However, that means that Data property now will return an object of type Object. The compiler cannot infer the actual data type at compile time, so it can choose the appropriate SomeMethod overload.

    You have to either provide an overload of SomeMethod that takes Object as a parameter, or remove the requirement to hold different such different types in your collection.

    Or you can go with a standard IEnumerable collection (like Array) and use the OfType<> extension method to get the subset of the collection of particular type.

提交回复
热议问题