2017-04-04 143 views
-4

我需要一个对象内的对象。 “主”对象需要3个字符串字段和1个包含另一个字符串的对象字段。 我发现我必须创建2个具有3个字符串字段的类,另一个具有一个字符串字段。 现在我的问题我如何获得第二类作为第一类中的对象?如何在一个对象内创建一个对象c#

+1

您使用哪种语言,C或C#?他们非常不同。 – Servy

+0

这个问题为什么用两种截然不同的语言标记? – Amy

+0

还有很多其他问题已经提出。 – 0perator

回答

0

由于问题的标题说,C#,让我们去了,并且使用一些语法糖:

using System; 

namespace Example 
{ 

    public class Child 
    { 
     public string Property1 { get; set; } 
    } 

    public class Parent 
    { 
     public string Property1 { get; set; } 
     public string Property2 { get; set; } 
     public string Property3 { get; set; } 
     public Child Property4 { get; set; } 
    } 

    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      var foo = new Parent 
      { 
       Property1 = "Hi", 
       Property2 = "there", 
       Property3 = "Svenja", 
       Property4 = new Child 
       { 
        Property1 = "Löffel" 
       } 
      }; 
      Console.WriteLine(foo.Property3); 
      Console.WriteLine(foo.Property4.Property1); 
      Console.ReadLine(); 
     } 
    } 
} 

Working Fiddle here

2

您将属性或字段添加到类型为第二个对象类型的第一个对象,例如

public class ChildObject 
{ 
    public string ChildObjectProperty1 {get; set;} 
} 

public class MainObject 
{ 
    public string Property1 {get; set;} 
    public string Property2 {get; set;} 
    public string Property3 {get; set;} 
    public ChildObject Property4 {get; set;} 
    public MainObject() 
    { 
     // Initialize Property4 to a new instance of a ChildObject 
     this.Property4 = new ChildObject(); 
    } 
} 
+0

这就是C#,顺便说一下,不是C. –