【发布时间】:2011-02-28 17:00:03
【问题描述】:
我需要将具体类型的通用列表转换为具体类型实现的接口的通用列表。此接口列表是对象的属性,我正在使用反射分配值。我只知道运行时的值。下面是我想要完成的一个简单的代码示例:
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。新的协变或逆变特征会有所帮助吗?
提前致谢。
【问题讨论】:
标签: .net generics reflection properties