C# - 匿名类型与特定类型 [英] C# - Anonymous type vs Specific Type

查看:72
本文介绍了C# - 匿名类型与特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

在这个例子中,我们可以使用匿名类型或创建一个类,并且两种方法都有相同的结果。

In this example we can use anonymous type or create a class and have the same result in both approach.

这些类型和哪个更好使用有什么区别?谢谢

What is difference between these type and which better to use? Thanks

 class Info
        {
            public string custName { get; set; }
            public string disName { get; set; }
        }
        static void  Main()
        {

            var result =
               from c in customers
               join d in distributors on c.State equals d.State

               //select new { custName = c.Last ,  disName = d.Name};
               select new Info { custName = c.Last, disName = d.Name };

            //foreach (var item in result)
            foreach (Info item in result)
            {
                Console.WriteLine(item.custName + " "  + item.disName);

            }







           Console.Read();
        }

推荐答案

" VAR"变量是强类型的。它们的类型是在编译时(不是运行时)确定的,并且等同于您创建自己的类的方式。它们的优点是可以节省您为一次性使用创建类的工作量。它们确实降低了代码的b $ b清晰度。有人在没有Visual Studio鼠标提示的帮助下阅读代码将不知道编译器确定的类型。 " VAR" LINQ和FOREACH非常方便。

"var" variables are strongly typed. Their type is determined at compile time (not run time) and are the equivalent to how you created your own class. Their advantage is saving you the effort of creating a class for a single use. They do reduce clarity of the code. Someone reading the code without the help of Visual Studio mouse over tips will not know the type determined by the compiler. "var" is very convenient for LINQ and FOREACH.


这篇关于C# - 匿名类型与特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆