I am using ParseLambda
from System.Linq.DynamicExpression
namespace. More info can be found on ScottGu's blog .
The following code throws Unknown identifier 'TeamType'
exception
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
is just an instance of UserInfo
;
My question is what can I do so TeamType
will be recognized, or how can I pass the enum as parameter.
Additional exceptions:
If I change condition
to Convert.ToInt32(CurrentUser.CurrentTeamType) == 1
, I get the following exception Expression of type 'Namespace.TeamType' cannot be used for parameter of type 'System.Object' of method 'Int32 ToInt32(System.Object)'
If I change condition
to (int)CurrentUser.CurrentTeamType == 1
, I get the following exception Unknown identifier 'int'
If I add namespace too like var condition = "CurrentUser.CurrentTeamType == App.BE.TeamType.Admin";
, I get Unknown identifier 'App'
. Please note that I have a reference to App.BE
namespace
Try using the full namespace to TeamType. Since you are using it in a string, it probably just needs you to be more specific.
UPDATE:
I think this answer will help you. You need to set up predefined types ahead of time.
有一个更简单的解决方案-只需使用枚举值的文本表示即可,即可以:
var condition = "CurrentUser.CurrentTeamType == \"Admin\"";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.