【问题标题】:Expression.Call and "Ambiguous Match Found"Expression.Call 和“找到模糊匹配”
【发布时间】:2010-10-04 21:16:58
【问题描述】:

我正在尝试编写一个表达式,该表达式将在属性上调用 ToString 并将其值分配给局部变量。但是,在带有 ToString 重载的对象实例上调用 ToString 会导致抛出“发现歧义匹配”异常。这是一个例子:

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?谢谢!

【问题讨论】:

    标签: c#-4.0 expression-trees


    【解决方案1】:

    替换:

    typeof(string).GetMethod("ToString")
    

    与:

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

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

    【讨论】:

    • 这正是我想要的,谢谢!我以前从未听说过 Type.EmptyTypes。您会推荐一本讨论此类问题的反思书吗?
    • Type.EmptyTypes 只是简写(并且比new Type[0] 稍微高效)。抱歉,我不是书迷,但只要仔细阅读 MethodInfoFieldInfoType 的源代码(除了Expression).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2016-02-11
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多