Why can't we declare var a = new List at class level?

前端 未结 5 2082
醉梦人生
醉梦人生 2021-01-18 23:27

I know we cannot do this at class level but at method level we can always do this.

var myList=new List // or something else like this
<         


        
5条回答
  •  终归单人心
    2021-01-18 23:54

    The compiler guys just didn't implement the support.

    It's entirely compiler magic, and the compiler doesn't actually put something into IL that says "figure out the type at runtime", it knows the type and builds it in, so it could've done that for members as well.

    It just doesn't.

    I'm pretty sure that if you asked an actual compiler guy on the C# compiler team, you'd get something official, but there's no magic happening here and it should be possible to do the same for members fields.

提交回复
热议问题