使用Convert.ChangeType在字符串和枚举之间进行转换

时间:2015-09-11 14:25:43

标签: c# casting expression expression-trees

我有一个代表通用过滤器表达式的类

SSTATE_CACHE

当我需要在IQueryable上应用过滤器时,我只需将此过滤器转换为LambdaExpression对象,并将此过滤器应用于DbSet实例,如下例所示

public class SimpleFilter : BaseRuleExpression
{
    public string field { get; set; }

    public string op { get; set; }

    public string data { get; set; }
}

var filter = new SimpleFilter() { field = "CustomerID", op = "eq", value = "1" }; ParameterExpression pe = Expression.Parameter( typeof( Customer ), "x" ); IQueryable<Customer> query = _ctx.Customers.AsQueryable<Customer>(); Expression<Func<Customer, bool>> lambda = (Expression<Func<Customer, bool>>)filter.ToExpression( query, pe ); var cList = _ctx.Customers.AsQueryable<Customer>().Where( lambda ) 方法如下:

ToExpression

问题发生在以下行,因为MemberExpression memberAccess = GetMemberExpression( field, pe ); ConstantExpression filter = Expression.Constant( Convert.ChangeType( data, memberAccess.Type ) ); Operator condition = (Operator)StringEnum.Parse( typeof( Operator ), op ); LambdaExpression lambda = BuildLambdaExpression( memberAccess, filter, pe, condition, data ); 方法在Convert.ChangeTypestring之间没有直接转换。

enum

我该如何解决这个问题?我可以检查目标中的类型枚举,并最终转换为ConstantExpression filter = Expression.Constant( Convert.ChangeType( data, memberAccess.Type ) ); 中的string吗?

1 个答案:

答案 0 :(得分:3)

我发现从TypeDescriptor获取转换器是一种更可靠的方式来转换各种类型。这是ASP.NET MVC Model Binding等技术使用的策略。

void Main()
{
    var converter = TypeDescriptor.GetConverter(typeof(Foo));
    Foo f = (Foo)converter.ConvertFromString("A");
    Console.WriteLine(f); // A
}

// Define other methods and classes here
public enum Foo {A, B, C}