2
我需要将具体类型的通用列表转换为具体类型实现的接口的通用列表。该接口列表是一个对象的属性,我使用反射来分配值。我只知道运行时的价值。下面是什么,我试图完成一个简单的代码示例:.net使用反射时的运行时类型转换
public void EmployeeTest()
{
IList<Employee> initialStaff = new List<Employee> { new Employee("John Smith"), new Employee("Jane Doe") };
Company testCompany = new Company("Acme Inc");
//testCompany.Staff = initialStaff;
PropertyInfo staffProperty = testCompany.GetType().GetProperty("Staff");
staffProperty.SetValue(testCompany, (staffProperty.PropertyType)initialStaff, null);
}
类是像这样定义:
public class Company
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private IList<IEmployee> _staff;
public IList<IEmployee> Staff
{
get { return _staff; }
set { _staff = value; }
}
public Company(string name)
{
_name = name;
}
}
public class Employee : IEmployee
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Employee(string name)
{
_name = name;
}
}
public interface IEmployee
{
string Name { get; set; }
}
有什么想法?
我正在使用.NET 4.0。新的协变或逆变特征会有帮助吗?
在此先感谢。
该列表将是新的,但员工将是旧的对象 – SWeko 2010-06-07 13:32:33
@SWeko:绝对。将编辑以使其更清晰。 – 2010-06-07 13:38:32
为了让事情更加复杂,Staff是一个IList,所以你不能只是实例化它,并添加新的元素,你也必须知道期望的实现...... – SWeko 2010-06-07 13:45:52