Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get delegate arguments inside delegate

Could someone please help me to understand how to get all parameters passed to delegate inside delegate itself?

I have class :

public class ShopManager : ShopEntities
{
    public ShopManager getWhere(Func<Object, Object> dataList)
    {
        var x = dataList.???; // how to get arguments?

        return this;
    }

    public Object getLike(Object dataValue)
    {
        return dataValue;
    }
}

Then i call it as :

ShopManager shopManager = new ShopManager()
var demo = shopManager.getWhere(xxx => shopManager.getLike("DATA"));

The question is : how to get passed parameters "xxx" and "DATA" inside method getWhere()?

Thanks in advance.

like image 513
Anonymous Avatar asked Sep 09 '26 06:09

Anonymous


2 Answers

You can't because it's the other way around. You can't get the arguments because the delegate does not hold them; the getWhere method will need to pass a value for the xxx parameter when invoking the delegate. The anonymous method that the delegate refers to will then receive this value as the xxx parameter, and in turn pass the string "DATA" as argument for the dataValue parameter when calling getLike. The argument values as such are not part of the delegate's state.

If you want to get information about the parameters as such (not their values), you can do that:

// get an array of ParameterInfo objects
var parameters = dataList.Method.GetParameters();
Console.WriteLine(parameters[0].Name); // prints "xxx"
like image 51
Fredrik Mörk Avatar answered Sep 11 '26 18:09

Fredrik Mörk


If you use:

public ShopManager getWhere(Expression<Func<Object, Object>> dataList)

then you can divide the Expression into its subexpressions and parse them. But I'm not sure if using a delegate like you do is even the right thing.

like image 43
CodesInChaos Avatar answered Sep 11 '26 18:09

CodesInChaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!