Will delegate any method with the params keyword?

I am trying to do the following:

public delegate void SomeMethod(params object[] parameters);

This is my delegate. And I have some method that will run this SomeMethod delegate (all passed) and return me the runtime.

   public TimeSpan BenchmarkMethod(SomeMethod someMethod, params object[] parameters)
    {
        DateTime benchmarkStart = DateTime.Now;

        someMethod(parameters);

        DateTime benchmarkFinish = DateTime.Now;
        return benchmarkFinish - benchmarkStart;
    }

I also have a method:

public abstract void InsertObjects (Company c);

So, I declare this:

SomeMethod dlg = new SomeMethod(InsertObjects);
TimeSpan executionTime = BenchmarkMethod(dlg, c);

But it doesn’t work, saying that “Overloading for“ InsertObjects ”does not match the delegate“ TestFactory.MeasuringFactory.SomeMethod. ”Is there a way to do this? .. Or should I change all my methods to accept params [] as an argument ? ..

+3
source share
3 answers

, , ( ). object[] Delegate.DynamicInvoke(object[] args).

Edit:

, MethodBase.GetParameters().Length , .

, , , , :

abstract class Benchmark
{
    TimeSpan Run()
    {
        Stopwatch swatch = Stopwatch.StartNew();
        // Optionally loop this several times and divide elapsed time by loops:
        RunMethod();
        swatch.Stop();
        return swatch.Elapsed;
    }

    ///<summary>Override this method with the code to be benchmarked.</summary>
    protected abstract void RunMethod()
    {
    }
}

, .

+4

params ?

. .

params - , , .

, , :


TimeSpan BenchmarkMethod(SomeMethod someMethod, params Company[] parameters)

:


Company company1 = null;
Company company2 = null;

//In BenchmarkMethod, company1 and company2 are considered to be part of 
//parameter 'parameters', an array of Company;
BenchmarkMethod(dlg, company1, company2);

, :


Company company1 = null;
object company3 = new Company();

BenchmarkMethod(dlg, company1, company3);

, company3 , - .

, , params , .

, , : Type variance

:


public delegate void SomeMethod(params object[] parameters);

, :


public abstract void InsertObjects (Company c);

:


SomeMethod dlg = new SomeMethod(InsertObjects);
TimeSpan executionTime = BenchmarkMethod(dlg, c);

, InsertObjects, , Company.

, , .

, :


public delegate void SomeMethod(params Company[] parameters);

public TimeSpan BenchmarkMethod(SomeMethod someMethod, params Company[] parameters) {
    DateTime benchmarkStart = DateTime.Now;
    someMethod(parameters);
    DateTime benchmarkFinish = DateTime.Now;
    return benchmarkFinish - benchmarkStart;
}

public void InsertObjects(object c) {
    Console.WriteLine(c);
}

, , .

: params .

+4

params - , . , , .

, , , , :

SomeMethod dlg = new SomeMethod(delegate(Object[] parameters)
{
    InsertObjects((Company)parameters[0]);
};
+2

Source: https://habr.com/ru/post/1716421/


All Articles