开发者

Can C#'s delegate methods take implicitly typed arguments?

I'm curious if it's possible to create a delegate method with implicitly typed arguments. Here's what I'm trying to accomplish. This sort of thing won't compile for me, but it should give you an idea of what I'm trying to accomplish.

here's the functions I want to call using delegates:

class MyClass
{
    ArrayList function1(int param1, int param2)
    {
        ...do something...
    }
    ArrayList function2(string param3)
    {
        ...do something...
    }
}

And here's the class that calls them:

class MyOtherClass
{
    delegate ArrayList delFunc(params object[] args);

    myOtherClass()
    {
        MyClass myClassInstance = new myClass();
        delFunc myDelFunc1 = myClassInstance.function1;
        delFunc myDelFunc2 = myClassInstance.function2;

        myDelFunc1(1,2);
        myDelFunc2("hello world");
    }


}

Obviously in this example you would just actually call the provided functions. What I'm actually trying to do, is create a wrapper function which allows you to provide a function as a delegate with any possible argument list.

The onl开发者_JS百科y solution I can come up with is to make the functions in MyClass take param lists as well. However, that would make it very confusing to anyone directly calling these functions. Here's what I mean:

class MyClass
{
    ArrayList function1(params object[] args)
    {
        ...do something...
    }
    ArrayList function2(params object[] args)
    {
        ...do something...
    }
}

Now it compiles, but I need to guess, or read comments, to find out what to pass into function1 and function2. Also, where it once failed at compile time, it now fails at runtime. All very bad things...

I'm thinking there may be some syntax I'm missing for doing something like this

delegate ArrayList delFunc(MatchAnyArgumentSignature);

Cheers, Rob


Just use Action<T> or Action<T1, T2, .....> :

public void Something(int arg1, int arg2, int arg3) {
  ...
}

and anywhere inside a method:

Action<int, int, int>  call = Something; 
call(1, 2, 3);

You cannot use var in this case.

Anyways, you shouldn't use ArrayList anymore.

Edit:

If those delegates should return something, there is Func<TResult>, Func<T1..TN, TResult>

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜