开发者

How to make generic linq expression even more "generic"

I have the following class with an expression property:

public class ClassWithExpression
{
    public Expression<Func<SomeAbstractBaseClass, object>> SomeExpression { get; set; }
}

I need an expression to be able to 开发者_如何学JAVAhandle all sub-classes of SomeAbstractBaseClass and all types of property selectors (int, string, decimal, etc). Eventually, the expression will be passed to a linq extension method like OrderBy. As it stands, it locks me into properties that appear on the base class only. The object prop selector is problematic when trying to pass in anything but a string prop.

I'd be okay with something like...

public class ClassWithExpression
{
    public Expression SomeExpression { get; set; }
}

... but nothing enforces that the expression is based on a sub-class of SomeAbstractBaseClass. Also, I'm not sure how I would pass an expression like that into the OrderBy extension method.

Any help would be appreciated, even if it's a complete change of direction. :)

EDIT:

Sorry I didn't mention it earlier, but I can't use generics to solve this problem. Unfortunately, I don't know the types at compile-time.


Use a generic type constraint:

public class ClassWithExpression<T> where T : SomeAbstractBaseClass
{
    public Expression<Func<T, object>> SomeExpression { get; set; }
}


Can you do something like this?

private Expression<Func<SomeAbstractBaseClass, object>> SomeExpression;

public void SetExpression<T>(Expression<Func<T, object>> expression)
    where T : SomeAbstractBaseClass
{
    SomeExpresssion = expression;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜