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

前端 未结 9 798
眼角桃花
眼角桃花 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:12

    With lamba expressions and class initializers you can get the same behaviour with a bit of effort.

    public class Example {
        public Action DoStuff;
        public Action DoStuffWithParameter;
        public Func DoStuffWithReturnValue;
    }
    
    class Program {
        static void Main(string[] args) {
            var x = new Example() {
                DoStuff = () => {
                    Console.WriteLine("Did Stuff");
                },
                DoStuffWithParameter = (p) => {
                    Console.WriteLine("Did Stuff with parameter " + p);
                },
                DoStuffWithReturnValue = () => { return 99; }
    
    
            };
    
            x.DoStuff();
            x.DoStuffWithParameter(10);
            int value = x.DoStuffWithReturnValue();
            Console.WriteLine("Return value " + value);
            Console.ReadLine();
        }
    }
    

    One problem with this solution that I just realized is that if you were to create fields in the Example class, the lambda expressions would not be able to access those fields.

    However, there is no reason that you could not pass the instance of Example to the lambda expressions which would give them access to any public state that example might hold. AFAIK that would be functionally equivalent to the Java Anonymous Inner Class.

    P.S. If you are going to vote an answer down, do us all a favour and add a comment as to why you disagree :-)

提交回复
热议问题