Difference between the implementation of var in Javascript and C#

后端 未结 5 761
情深已故
情深已故 2020-12-29 20:33

I would like to ask a theoretical question. If I have, for example, the following C# code in Page_load:

cars = new carsModel.carsEntities();

var mftQuery =          


        
5条回答
  •  北海茫月
    2020-12-29 21:06

    var in C# is dynamic at design time but staticly typed at compile time. You will see that if you do:

    var mftQuery = from mft in cars.Manufacturers
        where mft.StockHeaders.Any(sh=> sh.StockCount>0) 
        orderby mft.CompanyName
        select new {mft.CompanyID, mft.CompanyName};
    

    and then:

    mftQuery = "Hello world!";
    

    It will not compile and complain about missmatching types even though you didn't specify any type.

    This is a useful productivity enhancement because you can easily change return types to similar types without breaking anything and it is easier to write. A stupid example:

    foreach(var animal in GetCats()){
       Console.WriteLine(animal.Owner);
    }
    

    could be changed to:

    foreach(var animal in GetDogs()){
       Console.WriteLine(animal.Owner);
    }
    

提交回复
热议问题