这篇文章主要讲解了“C# 3.0对象和集合初始化怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C# 3.0对象和集合初始化怎么实现”吧!
Point类
public class Point { public int X { get; set; } public int Y { get; set; } }
对象类初始化可以这样定义了
Point p = new Point { X = 3, Y = 99 };
如果是集合初始化,主要继承了System.Collections.Generic.IEnumerable< T> ,并且有个公共方法Add可以进行初始化集合初始化
集合初始化例子具体如下
List< Point> Square = new List< Point> { new Point { X=0, Y=5 }, new Point { X=5, Y=5 }, new Point { X=5, Y=0 }, new Point { X=0, Y=0 } };
完整的例子源码
class Program { static List< Customer> CreateCustomers() { return new List< Customer> { new Customer(1) { Name = “Alex Roland”, City = “Berlin” }, new Customer(2) { Name = “Oliver Cox”, City = “Marseille” }, new Customer(3) { Name = “Maurice Taylor”, City = “London” }, new Customer(4) { Name = “Phil Gibbins”, City = “London” }, new Customer(5) { Name = “Tony Madigan”, City = “Torino” }, new Customer(6) { Name = “Elizabeth A. Andersen”, City = “Portland” }, new Customer(7) { Name = “Justin Thorp”, City = “London” }, new Customer(8) { Name = “Bryn Paul Dunton”, City = “Portland” } }; } static void Main(string[] args) { List< Customer> customers = CreateCustomers(); Console.WriteLine(”Customers:\n”); foreach (Customer c in customers) Console.WriteLine(c); }
感谢各位的阅读,以上就是“C# 3.0对象和集合初始化怎么实现”的内容了,经过本文的学习后,相信大家对C# 3.0对象和集合初始化怎么实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。