2010-10-04 46 views
8

我正在嘗試編寫一個表達式,它將在屬性上調用ToString並將其值分配給本地變量。但是,在對象實例上調用ToString(重載ToString)將導致拋出「發現Ambigous Match」異常。這裏有一個例子:Expression.Call和「發現不明確的匹配」

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)) 

); 

如果實例有重載的話,我該如何調用ToString?謝謝!

回答

13

替換:

typeof(string).GetMethod("ToString") 

隨着:

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

換句話說,獲得命名爲 「的ToString」 即接受零個參數(空型陣列)的製造方法。

+1

這正是我一直在尋找的,謝謝!我從來沒有聽說過Type.EmptyTypes。是否有反思書討論這樣的事情,你會推薦? – 2010-10-04 21:56:52

+0

Type.EmptyTypes只是簡寫(並且比''new Type [0]'更高效)。對不起,我不是一個讀書人,但是你只要仔細閱讀「MethodInfo」,「FieldInfo」和「Type」(除了'Expression'中的所有方法)的源代碼就會學到很多東西。 – 2010-10-04 22:02:37

+0

謝謝。你節省了我的一天 – 2013-05-13 08:09:42