如何在没有继承的情况下从另一个类获取值属性
本文关键字:另一个 获取 属性 情况下 继承 | 更新日期: 2023-09-27 18:03:27
我有类:
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());
}
}
所以,我想从Person类中获得属性ex: Firstname的值。
(我是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;
}