Edw*_*uay 2 c# syntax properties
以下程序将失败,因为合同未实例化.
当然我可以在构造函数中实例化它,但如果我有几十个属性和/或多个构造函数,我必须跟踪哪些实例化,等等.
当然,我可以使用完整的获取和集合以及私有字段变量等为这些属性创建大块.但这也会变得混乱.
有没有办法用漂亮的C#属性语法自动实例化这些集合?
using System;
using System.Collections.Generic;
namespace TestProperty232
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.FirstName = "Jim";
customer.LastName = "Smith";
Contract contract = new Contract();
contract.Title = "First Contract";
customer.Contracts.Add(contract);
Console.ReadLine();
}
}
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Contract> Contracts { get; set; }
public Customer()
{
//Contracts = new List<Contract>();
}
}
public class Contract
{
public string Title { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
没有这样的语法糖,但我想指出一些事情:
不,没有糖.在无参数构造函数中实例化它们,并在那里重定向所有其他构造函数,以便它始终执行.
class MyClass
{
//Many properties
public MyClass()
{
//Initialize here
}
public MyClass(string str) : this()
{
//do other stuff here
}
}
Run Code Online (Sandbox Code Playgroud)