以下程序将失败,因为合同未实例化。
当然我可以在我的构造函数中实例化它,但如果我有很多属性和/或多个构造函数,我必须跟踪哪些是实例化的,等等。
当然,我可以使用完整获取和设置以及私有字段变量等为这些属性创建大块。但这也会变得混乱。
有没有办法用漂亮的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; }
}
}
答案 0 :(得分:6)
没有这样的语法糖,但我想指出一些事情:
答案 1 :(得分:5)
不,没有糖。在无参数构造函数中实例化它们,并在那里重定向所有其他构造函数,以便它始终执行。
class MyClass
{
//Many properties
public MyClass()
{
//Initialize here
}
public MyClass(string str) : this()
{
//do other stuff here
}
}
答案 2 :(得分:1)
答案很长:这是怎么回事?
using System.Collections.Generic;
namespace proto
{
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Contract
{
public List<Customer> Customers { get; set; }
public string Title { get; set; }
}
public class ContractDemo
{
public Contract CreateDemoContract()
{
Contract newContract = new Contract
{
Title = "Contract Title",
Customers = new List<Customer>
{
new Customer
{
FirstName = "First Name",
LastName = "Last Name"
},
new Customer
{
FirstName = "Other",
LastName = "Customer"
}
}
};
return newContract;
}
}
}
答案 3 :(得分:1)
含糖或柠檬:你决定:(VS 2010 beta 2,FrameWork 4)
Customer customer = new Customer
{
FirstName = "Jim",
LastName = "Smith",
Contracts = new List<Contract> { new Contract { Title ="First Contract" } }
};
适用于您现有的类定义,但读起来感觉很难?
最好的,
答案 4 :(得分:0)
简短的回答是否。
答案 5 :(得分:0)
不确定你究竟在寻找什么,但你可以将它整理得有点像......
using System;
using System.Collections.Generic;
namespace TestProperty232
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer() {
FirstName = "Jim",
LastName = "Smith"
};
Contract contract = new Contract() {
Title = "First Contract"
};
customer.Contracts = new List<Contract>() { 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; }
}
}
答案 6 :(得分:0)
你可以让合同不是自动修改:
private List<Contract> _contracts;
public List<Contract> Contracts
{
get
{
if (_contracts == null)
{
_contracts = new List<Contract>();
}
return _contracts;
}
set
{
if (!_contracts.Equals(value))
{
_contracts = value;
}
}
}
这将使您不必显式实例化合同。