在 DynamicExpression 中传递枚举作为参数

Pass an Enum as parameter in DynamicExpression

我正在使用来自 System.Linq.DynamicExpression 命名空间的 ParseLambda。可以在 ScottGu's blog.

上找到更多信息

以下代码抛出 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 namespace

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

更新:

我认为 this answer 会对您有所帮助。您需要提前设置预定义类型。

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

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