我有一个名为employee的类,它有一个名为insurance的字段,类似于此类
public class Employee
{
public string Name;
public Insurance Insurance;
}
我有另一个叫保险的课程
public class Insurance
{
public int PolicyId;
public String PolicyName;
}
现在在主程序中我想做类似
的事情var myEmployee = new Employee();
myEmployee.Name = "Jhon";
myEmployee.Insurance.PolicyId = 123 ;
myEmployee.Insurance.PolicyName = "Life Time" ;
C#抱怨,我知道如何通过创建Insurance类的实例来修复它。
我的问题是我可以以某种方式使用类似
在主程序中以我想要的方式分配字段的值**
myEmployee.Insurance.PolicyId = 123 ;
myEmployee.Insurance.PolicyName = "Life Time" ;
** 我试过了
public class Employee
{
public Employee()
{
Insurance Insurance = new Insurance();
}
public String Name;
public Insurance Insurance;
public class Insurance
{
public int PolicyId;
public String PolicyName;
}
}
在我尝试的主要方法
class Program
{
static void Main(string[] args)
{
var joe = new Employee();
joe.Name = "Joe";
joe.Insurance.
}
我收到此错误 -
错误2“ConsoleApplication1.Employee.Insurance”与“ConsoleApplication1.Employee.Insurance”之间的歧义c:\ users \ lenovo \ documents \ visual studio 2012 \ Projects \ ConsoleApplication1 \ ConsoleApplication1 \ Program.cs 15 17 ConsoleApplication1
答案 0 :(得分:12)
您可以在Employee的构造函数中实例化保险,因此它会自动为您完成。您可以提供默认值,以确保在以后访问时尚未将其定义为有效。
public class Employee
{
Insurance Insurance { get; set; }
public Employee()
{
this.Insurance = new Insurance() { PolicyId = -1 };
}
}
public class Insurance
{
public int PolicyId { get; set; }
public string PolicyName { get; set; }
}
或者保持嵌套的类:
public class Employee
{
Insurance InsurancePolicy { get; set; }
public Employee()
{
this.InsurancePolicy = new Insurance() { PolicyId = -1 };
}
public class Insurance
{
public int PolicyId { get; set; }
public string PolicyName { get; set; }
}
}
答案 1 :(得分:11)
无需更改Employee
类,您可以使用对象初始值设定项:
var myEmployee = new Employee
{
Name = "Jhon",
Insurance = new Insurance
{
PolicyId = 123,
PolicyName = "Life Time"
}
};
或者,也许最好,您可以让Employee
类在其构造函数中创建Insurance
的新实例(如在其他答案中),或者另一个选项是执行此操作在Insurance
属性getter本身,所以只有在你使用它时它才被实例化。以下是后者的一个例子:
class Employee
{
private Insurance insurance;
public Insurance Insurance
{
get
{
if (insurance == null)
{
insurance = new Insurance();
}
return insurance;
}
}
}
最后,我建议您不要构建具有所有公共字段的类,除非您确实知道这是您想要的。相反,我会考虑在字段上使用属性。我已将其他建议纳入以下代码,并提供了我自己的建议:
public class Employee
{
public Employee()
{
this.Insurance = new Insurance();
}
// Perhaps another constructor for the name?
public Employee(string name)
: this()
{
this.Name = name;
}
public string Name { get; set; }
public Insurance Insurance { get; private set; }
}
public class Insurance
{
public int PolicyId { get; set; }
public string PolicyName { get; set; }
}
答案 2 :(得分:6)
当然,但是如何分配属于null
对象的内容?
您需要在Insurance
的构造函数中实例化Employee
。
public Employee()
{
this.Insurance = new Insurance();
}
编辑关于你的评论:
按照这种方法,您将能够使用两个点访问myEmplyee.Insurance.PolicyID
。构造函数是里面的 Employee的类,所以一旦实现它,你就不必输入比你已经尝试过的更多的东西了。
答案 3 :(得分:1)
您可以为您的员工编写一个构建器,以便实例化Insurance
public class Employee
{
public Employee()
{
this.Insurance = new Insurance();
}
public string Name;
public Insurance Insurance;
}