2017-04-04 5 views
-4

オブジェクト内にオブジェクトが必要です。 "main"オブジェクトには3つの文字列フィールドと、別の文字列を含むオブジェクトの1つのフィールドが必要です。 3つの文字列フィールドと1つの文字列フィールドを持つ2つのクラスを作成しなければならないことがわかりました。 今私の質問どのように第一クラスのオブジェクトとして第二クラスを取得するのですか?オブジェクト内にオブジェクトを作成する方法#

+1

お使いの言語はCまたはCですか?彼らは非常に異なっています。 – Servy

+0

なぜこの質問は2つの非常に異なる言語でタグ付けされていますか? – 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

タイプが第2のオブジェクトのタイプである第1のオブジェクトにプロパティまたはフィールドを追加します。

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である。 –

関連する問題