简体   繁体   English

在c#中创建实例时覆盖抽象方法

[英]Override abstract method upon instance creation in c#

In java, we can override or implement abstract methods upon instance creation as follows: 在java中,我们可以在实例创建时覆盖或实现抽象方法,如下所示:

AbstractClass test =new AbstractClass() 
{
    public void AbstractMethod(string i) {

    }
    public void AbstractMethod2(string i) {

    }
};

Is this possible in C#? 这可能在C#中吗? if Yes, what's the equivalent code 如果是,那么等价的代码是什么

Thanks 谢谢

This Java feature is called "anonymous class" , not "an override of method on instance creation". 此Java功能称为“匿名类” ,而不是“实例创建方法的覆盖”。 There is no identical feature in C#. C#中没有相同的功能。

C# took a different route - instead of providing convenience syntax for creation of subclasses, it expanded upon its delegate features, providing anonymous delegates and lambdas . C#采用了不同的路径 - 它不是为创建子类提供方便的语法,而是扩展了它的委托功能,提供了匿名委托lambda Lambdas let you plug in pieces of code. Lambdas让你插入代码片段。

You can achieve something very similar through clever use of lambdas: 通过巧妙使用lambda可以实现非常相似的东西:

public class BaseClass {

    public BaseClass(Action<string> abs1 = null, Action<string> abs2 = null){
       AbstractMethod1 = abs1 ?? s=>{};
       AbstractMethod2 = abs2 ?? s=>{};
    }

    public Action<string> AbstractMethod1 {get; private set;}
    public Action<string> AbstractMethod2 {get; private set;}
}

So you could use this definition like so: 所以你可以像这样使用这个定义:

new BaseClass( s=> Console.WriteLine(s), s=> Console.WriteLine(s));

You could also define all the methods as part of an interface and then construct a class with a concrete implementation of the interface (proxying the calls to the concrete implementation) -- I would call that the "Strategy" Pattern. 您还可以将所有方法定义为接口的一部分,然后构造一个具有接口的具体实现的类(代理对具体实现的调用) - 我将其称为“策略”模式。 But that's just a variation of this theme. 但这只是这个主题的一个变种。

Don't know Java , but this "smells" like Anonymous Types in C# . 不知道Java ,但这会像C# 匿名类型一样“闻起来”。

For example, you can write something like: 例如,您可以编写如下内容:

 var myNewType = new { 
                       Name = "Charles", 
                       Surname="Dickens", 
                       Age = 55 
                      };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM