c# - 这是一个大的表达式树吗? #4

标签 c# .net expression-trees

这不是“接近真实”的情况,但它表明如果表达式 API 在源类型中找到了合适的运算符,则表达式 API 不会在目标转换类型中查找运算符。

sealed class Foo
{
  public static explicit operator Bar(Foo foo) { return null; }
}

sealed class Bar
{
  public static implicit operator Bar(Foo foo) { return null; }
}

class Program
{
  public static void Blah(Bar bar) { }

  private static void Main()
  {
    Expression<Func<Foo, Bar>> expr1 = x => x;

    // fine, used implicit operator from Bar

    var param = Expression.Parameter(typeof(Foo), "x");

    var expr2 = Expression.Lambda<Func<Foo, Bar>>(
      Expression.Convert(param, typeof(Bar)),
      param);

    // fine, but used explicit operator from Foo!
  }
}

此外,如果模拟两种类型中用户定义运算符之间的歧义,C# 编译器根本不会编译转换,但表达式 API 将使用转换源类型中的运算符。

最佳答案

不,这不是表达式树错误。如果您无法为表达式树库提供足够的信息来执行您想要的操作,那么您将不得不接受其默认值。这些默认值没有任何理由需要遵循 C# 的规则;表达式树库不是 C# 编译器

关于c# - 这是一个大的表达式树吗? #4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1775603/

相关文章:

c# - 将字符串转换为 24 小时日期时间格式

c# - 如何使用四个自定义字节组成32位整数?

.net - 使用反射获取父类的名称

c# - 从 powershell 脚本记录到 csharp 程序(log4net - 日志文件)

c# - 使用 ExpressionVisitor 停止遍历

c# - 像在 C 中一样在 C# 中使用 struct - 可以吗?

c# - 在 wpf 中禁用 itemscontrol 上的鼠标滚轮

c# - 允许每个实例一个代理的最佳 WebBrowser 控件是什么?

c# - 为 string.Contains 构建表达式树

c# - 与 C# 中的嵌套表达式树作斗争