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

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

    Pass List Type in Generic

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

提交回复
热议问题