views:

63

answers:

6

Hi all,

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.

+1  A: 

You can't do it (easily). But I don't understand your idea. For what reason do you need to look into a dataList? This is just an anonymous method, you can call it and get results, you shouldn't need to examine or modify it at all.

What is your idea? Why not just call shopManager.getLike() ?

A.
+2  A: 

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"
Fredrik Mörk
+1  A: 

you can get the name of function by doing something like below.

  var x =  dataList.GetInvocationList().FirstOrDefault().Method.GetParameters();
  sring name = x.FirstOrDefault().Name 

this will print name as 'xxx'

saurabh
+1  A: 

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.

CodeInChaos
+1  A: 

Arguments are what you will provide while invoking the delegate via dataList(args), and not by the recipient of the invocation. If you want to provide additional information to getWhere() , you can try the following ....

public ShopManager getWhere(Func<Object, Object> dataList, params object[] additonalData)
{
 // inspect the additionalData
}   
mumtaz
A: 

Thanks for replies guys, i decided to use Expression> instead of common delegate. This allows to get both sides of expression - LHS and RHS.

For those who are interested in answer, this is it : http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0f6ca823-dbe6-4eb6-9dd4-6ee895fd07b5?prof=required

Thanks for patience and attention.

Tema