簡體   English   中英

如何在不繼承的情況下從另一個類獲取值屬性(在C#中)

[英]How to get value property from another class without inheritance in C#

我有課:

public class Employee{

 public int Id {get;set;}
 public string Firstname {get;set;}

}

public class Person
{
   //get value Firstname property from Employee class
     Employee emp = new Employee();
     foreach(var s in emp)
     {
       Console.WriteLine(s.Firstname.ToList());
     }

}

因此,我想獲取屬性ex的值:Person類中的名字。

(我是C#的新手)

我怎樣才能做到這一點?

您可以使用聚合 (這是當Employee知道Person且沒有它就無法操作的時候)。 范例:

public class Employee
{    
   public int Id {get;set;}
   public string Firstname => Person.FirstName;
   public Person Person {get;private set;}

   // this ctor is set to private to prevent construction of object with default constructor
   private Employee() {}

   public Employee(Person person) 
   { 
       this.Person = person;
   }
}

public class Person
{
   // We add property to Person as it's more generic class than Employee
   public string Firstname {get;set;}
}

要創建Employee,您可以使用以下代碼:

var jon = new Person { FirstName = "Jon" };
var employee = new Employee(jon);
Console.WriteLine(employee.FirstName); // OR
Console.WriteLine(employee.Person.FirstName);

您的FirstName屬性是一個字符串類型,因此您不能通過foreach循環對其進行交互,只能通過這種方式訪問​​它

public class Employee{

 public int Id {get;set;}
 public string Firstname {get;set;}

 public Employee(string name)
 {
   this.Firstname = name;
 }

}

public class Person
{
   Employee emp = new Employee("Foo");
   string s = emp.Firstname;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM