有没有其他方法可以在 C#/.NET 中实现覆盖(不是虚拟和覆盖)? [英] Is there any other way to implement Overriding (not virtual and override) in C# / .NET?

查看:53
本文介绍了有没有其他方法可以在 C#/.NET 中实现覆盖(不是虚拟和覆盖)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我在 C#/.NET 中不使用虚拟/抽象/覆盖的方法可以被覆盖,请给我一个例子.请提供一个例子......(我在想的是扩展方法我是否正确.....)

Could anyone tell me is there any other way a method can be overridden without using virtual/abstract/override in C#/.NET, Please provide me with an example.Please provide with an example... (what i am thinking is Extension methods am i correct.....)

推荐答案

您可以在方法上使用new"关键字来隐藏"未声明为抽象/虚拟的方法,但是如果该方法是从类型转换为基类的变量,它不会调用您的新方法.这类似于覆盖.

You can use the "new" keyword on your method to "hide" a method that was not declared as abstract/virtual, however if the method is called from a variable type-casted as the base class, it won't call your new method. This is the similar to overriding.

示例:

public class A
{
    public string GetName() { return "A"; }
}

public class B : A
{
    // this method overrides the original
    public new string GetName() { return "B"; }
}

扩展方法允许您向任何类添加新方法,即使您没有它们的源代码或它们是密封的.这与覆盖不同

Extension methods allow you to add new methods to any class even if you don't have their source code or they're sealed. This is not the same as overriding

public sealed class A // this could even be from a dll that you don't have source code to
{
}
public static class AExtensionMethods
{
    // when AdditionalMethod gets called, it's as if it's from inside the class, and it            
    // has a reference to the object it was called from. However, you can't access
    // private/protected fields.
    public static string AdditionalMethod(this A instance)
    {
        return "asdf";
    }
}

另一种选择是使用接口,这样您就可以拥有两个完全不同的对象,它们都具有相同的方法,但是当从类型转换为接口的变量调用时,它看起来类似于覆盖.

Another option is to use interfaces so that you can have two completely different objects that both have the same method, but when called from a variable type-casted as the interface, it looks similar to overriding.

您还可以使用一种形式的代理模拟框架,例如 Microsoft Moles 或 CastleWindsor -> 它们有一种实例化代理"对象的方法,该对象具有与真实对象相同的接口,但可以为每个对象提供不同的实现方法.

You could also use a form of Proxy Mocking framework like Microsoft Moles, or CastleWindsor -> They have a way of instantiating a "proxy" object that has the same interface as the real object, but can provide a different implementation for each method.

这篇关于有没有其他方法可以在 C#/.NET 中实现覆盖(不是虚拟和覆盖)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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