使用反射时的.net运行时类型转换

时间:2010-06-07 13:15:32

标签: .net generics reflection properties

我需要将具体类型的通用列表转换为具体类型实现的接口的通用列表。此接口列表是对象上的属性,我使用反射分配值。我只知道运行时的值。下面是我想要完成的一个简单的代码示例:

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。新的协变或逆变特征会有帮助吗?

提前致谢。

1 个答案:

答案 0 :(得分:3)

不,.NET 4方差在这里没有帮助:IList<T>是不变的,因为值可以进出(你可以添加项目,也可以获取它们)。

基本上这个演员阵容不会起作用(除非你使用数组及其方差属性;但这只是可怕的)。演员本身不是必需的 - SetValue只需要object - 但尝试使用错误的类型设置属性将失败。

您可以构建正确类型的 new 列表 - 但这意味着它将与现有列表分开。那可以接受吗? (列表元素本身将被共享,但如果您向一个列表添加新元素,则不会在另一个列表中显示。)