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

后端 未结 9 1505
猫巷女王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:58

    Just use an ArrayList and forget the MyData type.

    ArrayList myStuff = getStuff();
    float x = myStuff.OfType().First();
    SomeMethod(x);
    string s = myStuff.OfType().First();
    SomeMethod(s);
    

    The problem with MyData is that you're expecting the compiler to check a type that is only known at runtime. Compilers check types that are known at compile time.

提交回复
热议问题