如何强制调用一个C#派生的方法 [英] How to force call a C# derived method

查看:148
本文介绍了如何强制调用一个C#派生的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类是由一些工具生成的,所以我不能改变它。生成的类非常简单(没有接口,没有虚拟方法):

I have a class that is generated by some tool, therefore I can't change it. The generated class is very simple (no interface, no virtual methods):

class GeneratedFoo
{
  public void Write(string p) { /* do something */ }
}

在C#项目中,我们想提供一种方式,使我们可以插入一个不同的MyFoo实现。所以我想让MyFoo从GeneratedFoo派生

In the C# project, we want to provide a way so that we can plug in a different implementation of MyFoo. So I'm thinking to make MyFoo derived from GeneratedFoo

class MyFoo : GeneratedFoo
{
  public new void Write(string p) { /* do different things */ }
}

我有一个CreateFoo方法,将返回一个GeneratedFoo或MyFoo类的实例。但它总是调用GeneratedFoo中的方法。

Then I have a CreateFoo method that will either return an instance of GeneratedFoo or MyFoo class. However it always calls the method in GeneratedFoo.

GeneratedFoo foo = CreateFoo(); // if this returns MyFoo,
foo.Write("1"); // it stills calls GeneratedFoo.Write

这是expceted,因为它不是一个虚方法。

This is expceted since it is not a virtual method. But I'm wondering if there is a way (a hack maybe) to make it call the derived method.

感谢,

Ian

Thanks,
Ian

推荐答案

无法使方法为virtual,no。非虚方法在编译时静态链接,不能更改。

Without being able to make the method virtual, no. A non-virtual method is statically linked at compile time and can't be changed.

这篇关于如何强制调用一个C#派生的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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