con*_*low 11 .net c# expression-trees
在搜索用户定义的运算符时,表达式类应该更准确吗?
sealed class Foo
{
// just the private static method!
private static int op_Implicit() { return 1; }
public static implicit operator int(Foo foo) { return 2; }
}
public class Program
{
private static void Main()
{
var param = Expression.Parameter(typeof(Foo), "x");
// IndexOutOfRangeException was unhandled!
var lambda = Expression.Lambda<Func<Foo, int>>(
Expression.Convert(param, typeof (int)), param);
}
}
Run Code Online (Sandbox Code Playgroud)
此外,可以使用多个参数定义static op_Explicit或op_Implicitmethod,Expression类将此方法作为用户定义的运算符接受!
ps ExpressionTrees正在寻找带有BindingFlags.NonPublicflag的运算符,它允许搜索用户类型中的运算符,而不是System.Core.dll直接可见,但它也允许Expressions API查找"看起来像"用户定义的运算符的私有方法.但是C#规则不允许您定义和使用非公共运算符!我认为Expressions API的行为应该是相同的......