【发布时间】:2016-01-18 17:11:21
【问题描述】:
我正在使用来自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 命名空间
【问题讨论】:
标签: c# dynamic expression