【问题标题】:How to simulate ToString method by expression?#如何通过表达式模拟ToString方法?#
【发布时间】:2019-03-29 16:02:31
【问题描述】:

全部 如何通过表达式模拟ToString() 方法? 例如:

public class test
{
    public string id{get;set;}
}


ParameterExpression parameter1 = Expression.Parameter(typeof(class), "a");
MemberExpression member1 = Expression.PropertyOrField(parameter1, "id");
MethodCallExpression call1 = Expression.Call(typeof(int).GetMethod("ToString"), member1);
Console.WriteLine(call1);

但是系统在

报AmbiguousMatchException

MethodCallExpression call1 = Expression.Call(typeof(int).GetMethod("ToString"), member1);

【问题讨论】:

    标签: c# expression


    【解决方案1】:

    Int32.ToString() 方法有 4 种变体(不带参数、带 IFormatProvider 参数、带字符串格式参数等)。 您需要通过提供输入参数的 Type[] 来明确指定您需要哪一个(我假设您需要不带参数的那个):

    MethodCallExpression call1 = Expression.Call(typeof(int).GetMethod("ToString", Type.EmptyTypes), member1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多