使用反射强制转换泛型

时间:2018-10-18 14:49:03

标签: c# generics casting system.reflection

我有3个具有以下结构的课程。我有一个通用的方法来刷新集合以检查集合是否以任何方式更新。此方法可以正常工作,除非它在您要更新的模型中具有Observablecollection。

因此,在TestClassA中,我正在为Collectionrefresh调用通用的TestClassB方法。但是TestClassB的ObservableCollection不会更新。

public class TestClassA
{
   public ObservableCollection<TestClassB> CollectionA {get; set;}

   CollectionA.CollectionRefresh(CollectionB)    //Here CollectionB is the updated list
}

public class TestClassB
{
   public ObservableCollection<TestClassC> TestClassB {get; set;}
   public string Name {get; set;}
}

public class TestClassC
{
   public string FirstName {get; set;}
   public string LastName {get; set;}
}

现在要解决此问题,我已经用这种方式修改了方法。

public static void CollectionRefresh<T>(this ObservableCollection<T> collection, List<T> items)
{
   //Method Content

   PropertyInfo[] properties = typeof(T).GetProperties();


   foreach(PropertyInfo property in properties)
   {
      if (property.PropertyType.IsGenericType && typeof(ObservableCollection<>).IsAssignableFrom(property.PropertyType.GetGenericTypeDefinition()))
      {
         //I am getting the oldCollection and newList from somewherelse in the method.
         var collection1 = (dynamic)property.GetValue(oldCollection);
         var collection2 = (dynamic) property.GetValue(newList);

         collection1.CollectionRefresh(collection2);
      }
   }

   //Method Content
}

这不起作用,因为dynamic将是object,并且我希望将其强制转换为ObservableCollection<TestClassC>。如果我强制转换ObservableCollection<T>,则会给我错误的转换错误,因为此时T将是TestClassB,而我希望它是TestClassC。在将ObservableCollection<TestClassC>转换为collection1和collection2时,我的问题已解决,但是由于我正在执行泛型,因此我试图找到一种方法来对它进行泛型。

1 个答案:

答案 0 :(得分:0)

据我了解,您的最终目标是 $this->input()

其中void collection1.CollectionRefresh(collection2)

我想你要打电话

collection1.GetType()==collection2.GetType()==typeof(ObservableCollection<TestClassC>)

然后TestClassA testA = new TestClassA(); List<TestClassB> list = new List<TestClassB>(); testA.CollectionA.CollectionRefresh(list); 将是T,而TestClassB是您的目标财产。

ObservableCollection<TestClassC> CollectionB将返回一个对象,该对象不具有调用权限property.GetValue(TestClassB someB),因此您现在被卡住了,对吗?

这是一个嵌套的通用问题。如果您也将void CollectionRefresh(collection2)设为TestClassC,那将非常容易。

通常,我们将有一个非泛型基类,以便我们可以将其显式转换为该类。不幸的是,T2并不是从功能性ObservableCollection<T>类继承的。

这是我的建议。您必须同时使用表达式树和反射来获取ObservableCollection方法,然后调用它,但这可能是一个过大的选择。

无论如何,尝试一下。

CollectionRefresh
相关问题