2010-10-01 18 views
11

Qui è il contesto:Invocare un metodo di una classe generica

cerco di codificare un mapper per convertire i miei oggetti domain model a ViewModel Ojects dinamicamente. Il problema che ho capito, è quando provo a invocare un metodo di classe generica per riflessione ottengo questo errore:

System.InvalidOperationException: operazioni tardo legati non possono essere eseguite sui tipi o metodi per i quali ContainsGenericParameters è vero.

Qualcuno può aiutarmi a capire dov'è l'errore? Sarebbe molto apprezzato

Ecco il codice (ho cercato di semplificare esso):

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 "invocare un metodo di una classe generica" ​​è diverso da "invocare un metodo generico di una classe", la risposta non può risolvere la domanda qui. –

+0

@MasonZhang riaperto. – usr

risposta

16

è necessario chiamare GetMethod del tipo costruito constructed, non sulla definizione del tipo 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

Grazie! Funziona – dervlap

Problemi correlati