Expression.Call和"模糊匹配发现"

Jam*_*der 9 expression-trees c#-4.0

我正在尝试编写一个表达式,它将在属性上调用ToString并将其值赋给局部变量.但是,在ToString重载的对象实例上调用ToString会导致抛出"Ambigous Match Found"的异常.这是一个例子:

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

);
Run Code Online (Sandbox Code Playgroud)

如果实例有重载,我怎么能调用ToString?谢谢!

Kir*_*oll 14

更换:

typeof(string).GetMethod("ToString")
Run Code Online (Sandbox Code Playgroud)

附:

typeof(string).GetMethod("ToString", Type.EmptyTypes)
Run Code Online (Sandbox Code Playgroud)

换句话说,获取名为"ToString"的方法,该方法采用零参数(空类型数组).

  • 这正是我要找的,谢谢!我以前从未听说过 Type.EmptyTypes。是否有一本反思书讨论了您会推荐的此类事情? (2认同)