C# share code between classes

2019-04-30 03:48发布

问题:

In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?

Inheritance is not the solution as the classes already have a meaningful hierarchy.

Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?

EDIT:

ok, i guess we need a concrete example...

There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.

It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...

回答1:

If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:

  • Utilities (e.g. string formatting, parsing, ...)
  • Cross-cutting concerns (logging, security enforcement, ...)

For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.

public class Validator
{
  public bool IsValidName(string name);
}

class Patient
{
  private Validator validator = new Validator();
  public string FirstName
  {
     set
     {
         if (validator.IsValidName(value)) ... else ...
     }
  }
}

For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.

Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.

// Simplified example to explain:

public interface IPrint 
{ 
   public void Print(string); 
}

public class PrintA : IPrint
{
   public void Print(string input)
   { ... format as desired for A ... }
}

public class PrintB : IPrint
{
   public void Print(string input)
   { ... format as desired for B ... }
}

class MyPage
{
   IPrint printer;

   public class MyPage(bool usePrintA)
   {
      if (usePrintA) printer = new PrintA(); else printer = new PrintB();
   }

   public PrintThePage()
   {
      printer.Print(thePageText);
   }
}


回答2:

You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.

You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.

public interface IShareFunctionality { }

public static class Extensions
{
    public static bool DoSomething(this IShareFunctionality input)
    {
        return input == null;
    }
}

public class MyClass : Object, IShareFunctionality
{
    public void SomeMethod()
    {
        if(this.DoSomething())
            throw new Exception("Impossible!");
    }
}

This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.

We might need some more concrete examples of what you want to do though?



回答3:

A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.

You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.

As long as the source doesn't need to retain state, then use a static class with static method.

static public class MySharedMembers {
    static public string ConvertToInvariantCase(string str)  {
        //...logic
    }
    // .... other members
}


回答4:

If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.

If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.

I'm confused by the question: it seems you need to work on your basic OO understanding.



回答5:

Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx



回答6:

I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.

Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.



回答7:

I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.

You can preserve class hierarchy, at least visually and override behavior as needed.



回答8:

Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.

For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).

Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.



回答9:

To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.



回答10:

You have many options, TT, extension method, delegate, and lambda



标签: c# share