簡體   English   中英

C#將GetValue的結果從PropertyInfo轉換為通用列表

[英]C# casting the result of GetValue from PropertyInfo to a generic list

我試圖建立一個基於som XML文件中的值設置類屬性的應用程序。
一些類具有包含其子級列表的屬性。 由於我制作此程序的方式,必須通過propertyinfo類設置屬性。 我的問題是我無法確定子級列表( Derived2中的 ICollection)。
它必須強制轉換為通用列表( ICollectionHashSet ),因此我不必在每個派生類中復制粘貼相同的setChild方法。 我嘗試過將GetValue返回值強制轉換為ICollectionHashSetIENumerable ,但均無用
也許解決方案可能是使用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);
        }
    }
}
  1. Superclass沒有屬性,因此p實際上為null
  2. 您的財產名稱是PatientForloeb不是Derived1 ,也許您在尋找這個嗎?

     var p = parent .GetType() .GetProperties() .First(x => x.PropertyType.GetGenericArguments()[0] == children.GetType().GetGenericArguments()[0]); 
  3. HashSet<T>ICollection<T>ICollection<T>不是HashSet 。例如,在這種情況下,您期望發生什么:

     var list = new List<int>(); var collection = list as ICollection<int>; // okey var set = collection as HashSet<int>; // null 

但這不是唯一的問題,因為ICollection<T>不是協變的 另外,您甚至不需要使用as運算符就可以獲取值並進行設置。

實際上,您甚至不需要獲得財產的價值。如果仔細一下 ,您將獲得parent的財產的價值。然后嘗試將該值重新設置為parent的財產。即使這可行,一切都不會改變。您需要:

p.SetValue(parent, children);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM