简体   繁体   中英

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

I have classes:

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

}

So, I want to get value of property ex: Firstname from Person class.

(I'm newbie in C#)

How can I do that?

You can use aggregation (it's when Employee knows about Person and cannot operate without it). Example :

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

To create Employee you can use this code :

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

Your FirstName property is a string type so you can not interate over it by foreach loop you can only access it by this way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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