C#中:没有定义新的类创建一个抽象类的实例 [英] C#: Creating an instance of an abstract class without defining new class

查看:206
本文介绍了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?

推荐答案

通过兰巴表达式和类初始化,您可以用获得相同的行为。努力位

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();
    }
}



这个解决方案的一个问题,我只是意识到的是,如果你在实施例类创建领域,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.

然而,没有任何理由,你不能实例的实例传递给lambda表达式,这将使他们获得任何公开状态的例子可能持有。据我所知,这将是功能上等同于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。如果你要向下投票答案,做我们所有人一个忙,添加,为什么你不同意的意见: - )

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天全站免登陆