Linq 表达式找不到公共方法...:-/
我编写一个表达式来测试对象的属性(枚举)是否设置了某些标志。
下面的代码使用枚举的 HasFlag 函数测试对象的有效性是否“包含”星期一。
实际上,Call方法似乎没有找到相应的“HasFlag”...我在下面的代码中做错了什么?
using System;
using System.Linq.Expressions;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Expression exp = null;
var myValParam = Expression.Parameter(typeof(TestHehe), "val");
var myValTestValidityParam = Expression.Property(myValParam, "TestValidity");
Validity myVal = Validity.Monday;
// Gives 'True'
Console.WriteLine(myVal.HasFlag(myVal));
// test it
var myConst = Expression.Constant(myVal, myVal.GetType());
// here!!!!!!!!!!!!!!!!!!!!!!!!!!
exp = Expression.Call(myValTestValidityParam, "HasFlag", null, myConst);
// No method 'HasFlag' on type 'ConsoleApplication3.Validity'
// is compatible with the supplied arguments.
// just to be
Console.WriteLine(exp.ToString());
}
}
public class TestHehe
{
public Validity TestValidity { get; set; }
}
[Flags]
public enum Validity
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 4,
Friday = 8,
Saturday = 16,
Sunday = 32
}
}
I write a expression that will test if a property(enum) of a object have, or have not some flags set.
The code bellow test if the validity of an object "contains" or not Monday, using the HasFlag function of an Enum.
Actually, the Call method seems do not find a corresponding "HasFlag"... What I do wrong in the bellow code?
using System;
using System.Linq.Expressions;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Expression exp = null;
var myValParam = Expression.Parameter(typeof(TestHehe), "val");
var myValTestValidityParam = Expression.Property(myValParam, "TestValidity");
Validity myVal = Validity.Monday;
// Gives 'True'
Console.WriteLine(myVal.HasFlag(myVal));
// test it
var myConst = Expression.Constant(myVal, myVal.GetType());
// here!!!!!!!!!!!!!!!!!!!!!!!!!!
exp = Expression.Call(myValTestValidityParam, "HasFlag", null, myConst);
// No method 'HasFlag' on type 'ConsoleApplication3.Validity'
// is compatible with the supplied arguments.
// just to be
Console.WriteLine(exp.ToString());
}
}
public class TestHehe
{
public Validity TestValidity { get; set; }
}
[Flags]
public enum Validity
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 4,
Friday = 8,
Saturday = 16,
Sunday = 32
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在找这个吗?
HasFlag
想要一个Enum
作为参数,所以我向下转换了myVal
。Are you looking for this?
HasFlag
wants anEnum
as the parameter, so I downcastedmyVal
.