开发者

Restrict part of the lambda expression by type

开发者 https://www.devze.com 2023-04-03 05:17 出处:网络
I want to do something like this: public string DoSomething(Expression<Func<int>> expression)

I want to do something like this:

public string DoSomething(Expression<Func<int>> expression)
{
    //...
}

public void CallDoSomething()
{
    var myObj = new MyType();
    var result = DoSomething(() => myObj.IntProperty开发者_开发问答);
}

The goal is to do these three things within "DoSomething()": 1) Get a reference to myObj and do something with it 2) Get the name and value of the property "IntProperty" 3) Restrict myObj to be only of type MyType

I can do 1 and 2, but I cannot figure out how to do 3!

Please help.

Cheers


You can use the OfType<T>() method?


public static string DoSomething(Expression<Func<int>> expression) 
{
    MemberExpression memberExpression = (MemberExpression)expression.Body;
    Type type = memberExpression.Member.ReflectedType; // MyType

    bool check = typeof(MyType).IsAssignableFrom(type); // So you could check for base class
    // If you want to check for exactly one class, do 
    // bool type == typeof(MyType);

    if (!check) 
    {
        throw new Exception();
    }

    return null;
}

Is this what you want?


What you're doing is ... odd, and I don't know why the GetType solution isn't acceptable, but you could probably achieve something similar with another layer:

public string DoSomething(Expression<Func<int>> expression)
{
    //...
}

public void CallDoSomething()
{
    var myObj = new MyType();
    var result = CallHelper(myObj);
}

private string CallHelper(MyType m)
{
    return DoSomething(() => m.IntProperty);
}

CallHelper enforces the type restriction for you. I don't think there's any way to do it directly in the lambda expression (at least not without changing the signature of DoSomething), but maybe I'm missing something.

0

精彩评论

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

关注公众号