2010-10-01 2 views
11

Вот контекст:Вызов метода обобщенного класса

Я пытаюсь написать код картографа для преобразования моих DomainModel объектов в ViewModel Ojects динамически. Проблема, которую я получаю, это когда я пытаюсь вызвать метод родового класса путем отражения. Я получаю эту ошибку:

System.InvalidOperationException: операции с поздней строкой не могут выполняться по типам или методам, для которых ContainsGenericParameters истинно.

Может кто-нибудь помочь мне разобраться, где ошибка? Было бы весьма признателен

Вот код (я пытался упростил):

public class MapClass<SourceType, DestinationType> 
{ 

    public string Test() 
    { 
     return test 
    } 

    public void MapClassReflection(SourceType source, ref DestinationType destination) 
    { 
     Type sourceType = source.GetType(); 
     Type destinationType = destination.GetType(); 

     foreach (PropertyInfo sourceProperty in sourceType.GetProperties()) 
     { 
      string destinationPropertyName = LookupForPropertyInDestinationType(sourceProperty.Name, destinationType); 

      if (destinationPropertyName != null) 
      { 
       PropertyInfo destinationProperty = destinationType.GetProperty(destinationPropertyName); 
       if (destinationProperty.PropertyType == sourceProperty.PropertyType) 
       { 
        destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null); 
       } 
       else 
       { 

         Type d1 = typeof(MapClass<,>); 
         Type[] typeArgs = { destinationProperty.GetType(), sourceType.GetType() }; 
         Type constructed = d1.MakeGenericType(typeArgs); 

         object o = Activator.CreateInstance(constructed, null); 

         MethodInfo theMethod = d1.GetMethod("Test"); 

         string toto = (string)theMethod.Invoke(o,null); 

       } 
       } 
      } 
     } 


    private string LookupForPropertyInDestinationType(string sourcePropertyName, Type destinationType) 
    { 
     foreach (PropertyInfo property in destinationType.GetProperties()) 
     { 
      if (property.Name == sourcePropertyName) 
      { 
       return sourcePropertyName; 
      } 
     } 
     return null; 
    } 
} 
+0

@usr «вызов метода общего класса» отличается от «вызова универсального метода класса», ответ здесь не может решить вопрос здесь. –

+0

@MasonZhang вновь открыт. – usr

ответ

16

Вы должны вызвать GetMethod на конструируемого типа constructed, не по определению d1 типа.

// ... 

Type d1 = typeof(MapClass<,>); 
Type[] typeArgs = { destinationProperty.GetType(), sourceType.GetType() }; 
Type constructed = d1.MakeGenericType(typeArgs); 

object o = Activator.CreateInstance(constructed, null); 

MethodInfo theMethod = constructed.GetMethod("Test"); 

string toto = (string)theMethod.Invoke(o, null); 

// ... 
+0

Спасибо! Оно работает – dervlap