在动态表达式中传递枚举作为参数

本文关键字:枚举 参数 动态 表达式 | 更新日期: 2023-09-27 18:30:55

我正在使用System.Linq.DynamicExpression命名空间中的ParseLambda。更多信息可以在ScottGu的博客上找到。

以下代码引发Unknown identifier 'TeamType'异常

public bool CheckCondition()
{
    try
    {
        var condition = "CurrentUser.CurrentTeamType == TeamType.Admin";
        var currentUserParameter = Expression.Parameter(typeof(UserInfo), "CurrentUser");
        var dynamicExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { currentUserParameter}, null, condition);
        var result = dynamicExpression.Compile().DynamicInvoke(CurrentUserInfo);
        return Convert.ToBoolean(result);
    }
    catch(Exception ex)
    {
      // do some stuff then throw it again
      throw ex;
    }
}
public enum TeamType
{
    Admin = 1,
    AnotherType = 2
}
public class UserInfo
{
    public short UserId { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public TeamType CurrentTeamType { get; set; }
}

CurrentUserInfo只是UserInfo的一个实例;

我的问题是我能做什么才能被识别TeamType或者如何将枚举作为参数传递。

其他例外情况:

如果我将condition更改为Convert.ToInt32(CurrentUser.CurrentTeamType) == 1,则会出现以下异常 Expression of type 'Namespace.TeamType' cannot be used for parameter of type 'System.Object' of method 'Int32 ToInt32(System.Object)'

如果我将condition更改为(int)CurrentUser.CurrentTeamType == 1,则会出现以下异常Unknown identifier 'int'

如果我像var condition = "CurrentUser.CurrentTeamType == App.BE.TeamType.Admin";一样添加命名空间,我会得到Unknown identifier 'App'.请注意,我引用了App.BE命名空间

在动态表达式中传递枚举作为参数

尝试将完整的命名空间用于 TeamType。由于您在字符串中使用它,因此它可能只需要您更具体。

更新:

我认为这个答案会对你有所帮助。您需要提前设置预定义的类型。

有更简单的解决方案 - 只需使用枚举值的文本表示,即这将起作用:

var condition = "CurrentUser.CurrentTeamType == '"Admin'"";