【发布时间】:2014-05-04 23:35:34
【问题描述】:
我正在尝试构建一个应用程序,其中类的属性是根据 som XML 文件中的值设置的。
一些类具有由其子项列表组成的属性。由于我制作这个程序的方式,必须通过 propertyinfo 类设置属性。我的问题是我无法获取子列表(Derived2 中的 ICollection)。
它必须转换为通用列表(ICollection 或 HashSet),因此我不必在每个派生类中复制粘贴相同的 setChild 方法。
我已经尝试将 GetValue 返回值转换为 ICollection、HashSet 或 IENumerable,但没有任何效果。
也许解决方案是使用 PropertyInfo 类的另一种方法?
一个稍微简化的代码示例代码:
public interface Superclass
{}
public class Derived1 : Superclass {}
public class Derived2 : Superclass
{
public Derived2()
{
PatientForloeb = new HashSet<Derived1>();
}
public virtual ICollection<Derived1>Derived1{ get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Derived1> children = new List<Derived1>();
children.Add(new Derived1());
var parent = new Derived2();
setChild(parent, children);
}
private static void setChild(Superclass parent, List<Derived1> children)
{
foreach (var child in children)
{
var p = (parent.GetType().GetProperty(child.GetType().Name)); // This is ugly, should be based on type not name, but it works for my app.
var pi = p.GetValue(parent) as HashSet<Superclass>; ///////////<-------This gives null. This is the problem.
pi.add(child);
}
}
}
【问题讨论】:
标签: c# covariance contravariance propertyinfo