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

前端 未结 5 2050
醉梦人生
醉梦人生 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:33

    It's not as simple as implementing var in a method since you also have to take into acccount different modifiers and attributes like so:

    [MyAttribute()] protected internal readonly var list = new List<T>();
    

    What I would really have liked is a type-inferenced const!

    public const notFoundStatus = 404; // int
    
    0 讨论(0)
  • 2021-01-18 23:34

    There are technical issues with implementing this feature. The common cases seem simple but the tougher cases (e.g., fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not.

    See Eric Lippert's blog for an in-depth explanation: Why no var on fields?

    0 讨论(0)
  • 2021-01-18 23:36

    The var keyword was invented specific to support anonymous types. You are generally NOT going to declare anonymous types at the class level, and thus it was not implemented.

    Your example statement

    var myList=new List<string>
    

    is not a very good example of how to use the var keyword since it's not for the intended purpose.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 23:56

    Pass List Type in Generic

    class Class1
    {
        public void genmethod<T>(T i,int Count)
        {
    
    
            List<string> list = i as List<string>;
    
            for (int j = 0; j < Count; j++)
            {
                Console.WriteLine(list[j]);
            }
        }
        static void Main(string[] args)
        {
            Class1 c = new Class1();
            c.genmethod<string>("str",0);
            List<string> l = new List<string>();
            l.Add("a");
            l.Add("b");
            l.Add("c");
            l.Add("d");
            c.genmethod<List<string>>(l,l.Count);
    
            Console.WriteLine("abc");
            Console.ReadLine();
        }
    }
    
    0 讨论(0)
提交回复
热议问题