我在ParseLambda
命名空间中使用System.Linq.DynamicExpression
。更多信息可以在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
命名空间
答案 0 :(得分:1)
答案 1 :(得分:0)
有更简单的解决方案 - 只需使用枚举值的文本表示,即这将起作用:
var condition = "CurrentUser.CurrentTeamType == \"Admin\"";