Is it possible to override a method in a class in

2019-06-05 07:02发布

I've included a dll file into my windows form project. 1. Is it possible to override a particular class entirely? 2. Is it possible to add a new method to a particular class in the dll file? 3. Is it possible to override a method in a class in the dll?

Alternatives I would prefer to avoid: I know I can use extension methods to create static new methods. I can also inherit from a particular class and then add new methods to the derived class.

What i'm trying to achieve: i have to create a project now and add it to a larger project as a dll file. but we've been told that we'll need to add more functionality to the original project next month. I'm trying to figure out the best way to go about this. the smaller project is based on mvc design.

标签: c# oop
2条回答
ら.Afraid
2楼-- · 2019-06-05 07:30

What i'm trying to achieve: i have to create a project now and add it to a larger project as a dll file. but we've been told that we'll need to add more functionality to the original project next month. I'm trying to figure out the best way to go about this. the smaller project is based on mvc design.

The current best practice is to use inversion of control (eg. ninject) for these kind of things, if you have a central place for all you dependencies you can wire them up however you like at runtime, intercepting bits and pieces as you wish.

查看更多
干净又极端
3楼-- · 2019-06-05 07:39

You can certainly override a virtual method which you're inheriting from a class in a class library. You do this any time you override object.ToString(), for example!

You can't "override a class entirely" though - I don't know what that would even mean. Likewise you can't add a method to an existing class although you can:

  • Use extension methods to "pretend" to add another method (but no state, and no properties)
  • Derive from the class (assuming it's not sealed) and declare your own extra methods

If you could tell us what you're trying to achieve, it would be easier to advise you on how to proceed.

EDIT: When you need to add more functionality to the original project, just add it to the original project. Is there any reason you wouldn't be able to change that project later?

查看更多
登录 后发表回答