我有一个名为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在抱怨,我知道如何通过创建保险类的实例来修复它。
我的问题是,我是否可以在主程序中用类似的方法为字段赋值
**
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

最佳答案

您可以在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; }
    }
}

07-27 21:41