简体   繁体   English

初始化嵌套对象属性

[英]Initializing nested object properties

I have a class called employee which has a field called insurance which is of type insurance like this 我有一个名为employee的类,它有一个名为insurance的字段,类似于此类型的保险

public class Employee
{
    public string Name;
    public Insurance Insurance;
}

I have another class called Insurance 我有另一个名为保险的班级

public class Insurance
{
    public int PolicyId;
    public String PolicyName;
} 

Now in the main program i want to do something like 现在在主程序中我想做类似的事情

var myEmployee = new Employee();
myEmployee.Name = "Jhon";
myEmployee.Insurance.PolicyId = 123 ;
myEmployee.Insurance.PolicyName = "Life Time" ;

C# is complaining and i know how to fix it by creating a instance of the Insurance class. C#抱怨,我知道如何通过创建Insurance类的实例来修复它。

My question is can i somehow assign the values for the fields in the way i want to do it in the main program using like 我的问题是我可以以某种方式为我想在主程序中使用的方式分配字段的值

** **

myEmployee.Insurance.PolicyId = 123 ;
myEmployee.Insurance.PolicyName = "Life Time" ;

** I tried ** 我试过了

 public class Employee
    {

        public Employee()
        {
            Insurance Insurance = new Insurance();
        }

        public String Name;
        public Insurance Insurance;



        public class Insurance
        {
            public int PolicyId;
            public String PolicyName;
        } 
    }

In the main method when i try 在我尝试的主要方法

class Program
    {
        static void Main(string[] args)
        {
            var joe = new Employee();
            joe.Name = "Joe";
            joe.Insurance.

        }

I get this error- 我得到这个错误 -

Error 2 Ambiguity between 'ConsoleApplication1.Employee.Insurance' and 'ConsoleApplication1.Employee.Insurance' c:\\users\\lenovo\\documents\\visual studio 2012\\Projects\\ConsoleApplication1\\ConsoleApplication1\\Program.cs 15 17 ConsoleApplication1 错误2“ConsoleApplication1.Employee.Insurance”和“ConsoleApplication1.Employee.Insurance”之间的歧义c:\\ users \\ lenovo \\ documents \\ visual studio 2012 \\ Projects \\ ConsoleApplication1 \\ ConsoleApplication1 \\ Program.cs 15 17 ConsoleApplication1

You could instantiate Insurance in Employee's constructor so it is done automatically for you. 您可以在Employee的构造函数中实例化Insurance,这样就可以自动完成。 You could provide it default values to ensure it is understood that is not yet defined to be valid when accessed later on. 您可以提供默认值,以确保在以后访问时尚未将其定义为有效。

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; }
}

Or to keep the classes nested: 或者保持嵌套的类:

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; }
    }
}

Without requiring changes to your Employee class, you could use object initializers: 无需更改Employee类,您可以使用对象初始值设定项:

var myEmployee = new Employee 
{
    Name = "Jhon",
    Insurance = new Insurance
    {
        PolicyId = 123,
        PolicyName = "Life Time"
    }
};

Alternatively, and maybe preferably, you can have the Employee class create a new instance of Insurance either in its constructor (as in the other answers), or one other option would be to do it in the Insurance property getter itself, so it's instantiated only if you use it. 或者,也许最好,您可以让Employee类在其构造函数中创建一个新的Insurance实例(如在其他答案中),或者另一个选项是在Insurance属性getter本身中执行它,因此它仅实例化如果你使用它。 Here's an example of the latter: 以下是后者的一个例子:

class Employee 
{
    private Insurance insurance;

    public Insurance Insurance
    {
        get
        {
            if (insurance == null)
            {
                insurance = new Insurance();
            }
            return insurance;
        }
    }
}

Lastly, I would suggest that you don't build classes that have all public fields unless you really know that's what you want. 最后,我建议您不要构建具有所有公共字段的类,除非您确实知道这是您想要的。 Instead, I would consider using properties over fields. 相反,我会考虑在字段上使用属性 I have incorporated other's suggestions into the following code, and provided my own: 我已将其他建议纳入以下代码中,并提供了我自己的建议:

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; }
}

Of course, but how are you going to assign something that is belonging to a null object? 当然,但是如何分配属于null对象的东西呢? You need to instantiate Insurance in Employee 's constructor. 您需要在Employee的构造函数中实例化Insurance

public Employee()
{
     this.Insurance = new Insurance();
}

EDIT Regarding your comment: Following this approach you will be able to access myEmplyee.Insurance.PolicyID with two dots . 编辑关于您的评论:按照这种方法,您能够访问带有两个点的 myEmplyee.Insurance.PolicyID The constructor is inside Employee's class, so you won't have to type anything more than what you already tried to do, once you implement it. 构造函数位于 Employee的类中,因此一旦实现它,您就不必输入任何比您已经尝试过的更多的东西。

You can write a constructor for your employee that will instantiate Insurance 您可以为您的员工编写一个构造函数来实例化Insurance

public class Employee
{
    public Employee()
    {
        this.Insurance = new Insurance();
    }
    public string Name;
    public Insurance Insurance;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM