In C#, why can't a List object be stored in a List<object> variable

前端 未结 14 1656
别跟我提以往
别跟我提以往 2020-11-22 03:42

It seems that a List object cannot be stored in a List variable in C#, and can\'t even be explicitly cast that way.

List sl = new List

        
14条回答
  •  Happy的楠姐
    2020-11-22 04:24

    Such covariance on generics is not supported, but you can actually do this with arrays:

    object[] a = new string[] {"spam", "eggs"};
    

    C# performs runtime checks to prevent you from putting, say, an int into a.

提交回复
热议问题