2010-10-04 6 views
8

Sto provando a scrivere un'espressione che chiamerà ToString su una proprietà e assegnerà il suo valore a una variabile locale. Tuttavia, chiamando ToString su un'istanza dell'oggetto con un sovraccarico di ToString, viene generata un'eccezione di "Ambigous Match Found" da lanciare. Ecco un esempio:Expression.Call e "Ambita corrispondenza trovata"

var result = Expression.Variable(typeof(string), "result"); 
var matchTypeParameter = Expression.Parameter(typeof(MatchType), "matchType"); 
var targetProperty = Expression.Property(leadParameter, target); 

var exp = Expression.Block(
    //Add the local current value variable 
    new[] { result }, 

    //Get the target value 
    Expression.Assign(result, Expression.Call(targetProperty, typeof(string).GetMethod("ToString"), null)) 

); 

Come posso chiamare ToString se l'istanza ha sovraccarichi per esso? Grazie!

risposta

13

Sostituire:

typeof(string).GetMethod("ToString") 

Con:

typeof(string).GetMethod("ToString", Type.EmptyTypes) 

In altre parole, ottiene il metodo denominato "ToString" che prende zero argomenti (tipo array vuoto).

+1

Questo era esattamente quello che stavo cercando, grazie! Non ho mai sentito parlare di Type.EmptyTypes prima. C'è un libro di riflessioni che discute cose come questa che consiglieresti? –

+0

Type.EmptyTypes è solo una scorciatoia (e leggermente più efficiente di) 'new Type [0]'. Scusate, non sono una persona di un libro, ma imparerete un * lotto * solo esaminando il codice sorgente in 'MethodInfo',' FieldInfo' e 'Type' (oltre a tutti i metodi in' Expression'). –

+0

Grazie. Tu salvi la mia giornata –

Problemi correlati