C#:在不定义新类的情况下创建抽象类的实例 [英] C#: Creating an instance of an abstract class without defining new class

查看:32
本文介绍了C#:在不定义新类的情况下创建抽象类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它可以在 Java 中完成,因为我过去广泛使用过这种技术.下面将显示 Java 中的一个示例.(附加问题.这种技术叫什么?如果没有名字,很难找到这样的例子.)

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 technique called? It's hard to find an example of this without a name.)

public abstract class Example {
   public abstract void doStuff();
}

public class StartHere{
   public static void main(string[] args){
      Example x = new Example(){
         public void doStuff(){
            System.out.println("Did stuff");
         }            
      };
      x.doStuff();
   }
}

现在,我的主要问题是,这也可以在 C# 中完成吗,如果可以,怎么做?

Now, my main question would be, can this also be done in C#, and if so, how?

推荐答案

使用 Lamba 表达式和类初始值设定项,您只需稍加努力即可获得相同的行为.

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<int> DoStuffWithParameter;
    public Func<int> 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();
    }
}

我刚刚意识到这个解决方案的一个问题是,如果您要在 Example 类中创建字段,则 lambda 表达式将无法访问这些字段.

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.

但是,没有理由不能将 Example 的实例传递给 lambda 表达式,这将使它们能够访问该示例可能持有的任何公共状态.AFAIK 在功能上等同于 Java 匿名内部类.

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 :-)

这篇关于C#:在不定义新类的情况下创建抽象类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆