“运行时覆盖方法” C#
我想在自定义 dll 中重写 ClassA 的 Print 方法。
public ClassA
{
public void Print( string arg1, string arg2, string arg3, string arg4 )
{
}
}
这在 C# 中可能吗?
I want to override method Print of a ClassA in a custom dll.
public ClassA
{
public void Print( string arg1, string arg2, string arg3, string arg4 )
{
}
}
Is this possible in C# ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信微软研究院的 Moles 也做了类似的事情。他们有一个系统,允许您覆盖例如
DateTime.Now
的工作,强制它返回特定的日期/时间。看看 http://research.microsoft.com/en-us /projects/pex/default.aspx 了解更多信息。
I believe Moles from Microsoft Research does something similar. They have a system that allows you to override the working of e.g.
DateTime.Now
, forcing it to return a specific date/time.Have a look at http://research.microsoft.com/en-us/projects/pex/default.aspx for more information.
这与您所要求的不太一样,但它达到了类似的效果...
为什么不为您的操作定义一个接口。 ClassA 实现该接口。您的自定义策略也实现该接口。 ClassA 在启动时(实例化 ClassA 时)在内部创建接口的“默认”实现,但也有一个允许设置接口的属性。该接口甚至可以允许自定义策略指定它实际实现的接口的哪些成员:
您可以将自定义策略指定为 IStrategy 接口的一部分,以指示它不会“覆盖”特定操作。也许它可以返回一个
bool
而不是 void,或者也许每个操作都可以有一个out bool
参数,如果自定义策略未覆盖某个操作,该参数将设置为 false。根据可以覆盖的操作数量,您甚至可以考虑将每个操作置于其自己的接口中。如果在不实现某些其他操作的情况下实现一个操作是不合理的,则可以将操作分组到一个接口中。
This is not quite the same thing as you are asking, but it achieves a similar effect...
Why not define an interface for your operations. ClassA implements the interface. Your custom Strategies also implement the interface. ClassA internally creates the "default" implementation of the interface at startup (when ClassA is instantiated), but also has a property that allows the interface to be set. The interface might even allow the custom Strategy to specify which members of the interface that it actually implements:
You could specify as part of the IStrategy interface a way for the custom Strategy to indicate that it is not "overriding" a particular operation. Perhaps it could return a
bool
rather than a void or perhaps each operation could have anout bool
parameter that is set to false if the custom Strategy has not overridden an operation.Depending on how many operations can be overridden, you might even consider putting each operation its own interface. Operations could be grouped in an interface if it is not reasonable to implement one operation without also implementing some other operations.
您的第一个问题:该方法未标记为虚拟的。您不能
重写
非虚拟方法。至于问题,这完全取决于
ClassA
是如何实例化和使用的。例如,如果您可以控制派生类型的实例化和使用,您可以在运行时创建派生类型。Your first problem: the method is not marked
virtual
. You cannotoverride
a non-virtual method.As for the question, it all depends how
ClassA
is instantiated and used. You could for example create a derived type at runtime, if you can control the instantiation and usage of it.