C#: Creating an instance of an abstract class without defining new class

前端 未结 9 812
眼角桃花
眼角桃花 2020-12-29 04:25

I know it can be done in Java, as I have used this technique quite extensively in the past. An example in Java would be shown below. (Additional question. What is this techn

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 05:16

    While all good answers, most of the work arounds suggested rely on C# 3.0

    So, for the sake of completeness, I'll add another solution that uses neither lambdas nor Func type (Granted that, as Matt Olenik mentioned in the comments, one could generalize the below delegates to work the same way.). For those, like me who may still be working with C# 2.0. Maybe not the best solution, but it works.

    public class Example
    {
        public delegate void DoStuffDelecate();
        public DoStuffDelecate DoStuff;
        public delegate void DoStuffWithDelecate(int n);
        public DoStuffWithDelecate DoStuffWithParameter;
        public delegate int DoStuffWithReturnDelecate();
        public DoStuffWithReturnDelecate DoStuffWithReturnValue;
    }
    
    class Program
    {
        static int MethodWithReturnValue()
        {
            return 99;
        }
        static void MethodForDelecate()
        {
            Console.WriteLine("Did Stuff");
        }
        static void MethodForDelecate(int n)
        {
            Console.WriteLine("Did Stuff with parameter " + n);
        }
    
    
        static void Main(string[] args)
        {
            var x = new Example();
            x.DoStuff = MethodForDelecate;
            x.DoStuffWithParameter = MethodForDelecate;
            x.DoStuffWithReturnValue = MethodWithReturnValue;
    
            x.DoStuff();
            x.DoStuffWithParameter(10);
            int value = x.DoStuffWithReturnValue();
            Console.WriteLine("Return value " + value);
            Console.ReadLine();
        }
    }
    

提交回复
热议问题