Is it possible to use a delegate to call a class method without an instance?

The interviewer asked me that he had a heavy class with a number of methods. At the moment, he should have only one method.

He asked me if C # delegates can call me this method without instantiating the class?

And he said that delegates can help us this way.

I was looking for him. I tried to run it on VS, but I think I will need to initialize the class.

Take a look at this snippet -

public class HomeController : Controller
{

    public ActionResult test()
    {            
        NumberChanger nc1 = new NumberChanger( /*what to do here!
                                            can i call sum method of class abc*/);

        return View();
    }
}

public delegate int NumberChanger(int n, int m);

public class abc
{
    int a;
    int b;

    public int sum(int a, int b) {
        return a + b;
    }

}
+3
source share
2 answers

If you need to use a non-static method, you should probably use the new NumberChanger (new paragraph (). Sum)
Try

0
source

1 .

, , :

class TestClass
{
    private static TestClass DummyInstance;

    public static Action GetShowAsDelegate()
    {
        DummyInstance = DummyInstance ?? new TestClass();
        return (DummyInstance.Show);
    }

    public void Show()
    {
        Console.WriteLine("It works!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var show = TestClass.GetShowAsDelegate();
        show();
    }
}

, , Show(). , . Show, , .

0

All Articles