C#在类之间共享代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1878419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:35:14  来源:igfitidea点击:

C# share code between classes

c#share

提问by mson

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

在使用 C# 的 Visual Studio 2008 中,跨多个类和源文件共享代码的最佳方式是什么?

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?

是否有一些类似于 C 包含文件的简洁功能,让您可以在另一个类中的任何位置插入代码?

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.

该域中有数百个类具有经过深思熟虑的类层次结构。现在,许多这些类需要打印。有一个处理打印的实用打印机类。假设有 3 种不同的打印方法,它们依赖于正在打印的类。调用打印方法(6 行)的代码是我试图避免在所有不同的客户端类页面之间复制和粘贴的代码。

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...

如果人们不会假设他们对操作的领域了解更多,那就太好了 - 特别是当他们特别提到不适合的技术时......

采纳答案by Eric J.

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.

关于其他评论中讨论的 PrintA 与 PrintB 示例,这听起来像是工厂模式的绝佳案例。您定义一个接口,例如 IPrint,类 PrintA 和 PrintB,它们都实现 IPrint,并根据特定页面的需要分配 IPrint 的实例。

// 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);
   }
}

回答by John K

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.

AC# 实用程序类将起作用。它的作用类似于公共代码的中央注册表(或类似于 VB.NET 模块构造)——它应该包含不特定于任何类的代码,否则它应该附加到相关类。

You don'twant 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
}

回答by Coxy

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.

老实说,我想不出像 Visual C# 中的包含这样的东西,也想不出为什么你会想要这个功能。也就是说,部分类可以做一些听起来像你想要的事情,但使用它们可能会与你的“类已经有一个有意义的层次结构”要求发生冲突。

回答by antik

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.

如果它们不在同一个命名空间中,请在 usings 指令中添加要使用的类的命名空间,它应该与上述相同。

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

我对这个问题感到困惑:似乎您需要对基本的 OO 理解进行工作。

回答by Jerry Fernholz

回答by GrayWizardx

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.

我已经不确定你所说的“有意义的”结构到底是什么意思,但这听起来像是一个可以使用基类实现的地方。尽管不像 C++ 多重继承那样“冗长”,但您可能会从使用链式基类实现重用公共函数中获得一些好处。

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

您可以至少在视觉上保留类层次结构并根据需要覆盖行为。

回答by Khanzor

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.

您不能像在 C 中那样通过预处理器指令加载您希望添加到 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?

我们可能需要一些更具体的例子来说明你想要做什么?

回答by Dennis C

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

你有很多选项,TT、扩展方法、委托和 lambda

回答by No Refunds No Returns

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.

我不知道包含文件部分的方法,但我们经常做的一件事是添加现有文件并从其当前位置“链接”它。例如,我们有一个 assemblyInfo.cs 文件,每个项目都从解决方案目录中引用该文件。我们更改一次,所有项目都具有相同的信息,因为它们指的是同一个文件。

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

否则,关于在 common.dll 中重构“通用”例程的建议是我在 .Net 中提出的最好的建议。

回答by Josh

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).

例如,创建一个包含打印所需逻辑的“PrintingService”。然后,您可以让需要打印的类依赖于该服务(通过构造函数或需要该服务的方法中的参数)。

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.

我在这些方面的另一个技巧是为基本功能创建接口,然后使用接口进行编码。例如,我有一堆报告类,用户可以通过传真、电子邮件或打印这些报告类。我没有为每个方法创建方法,而是为每个方法创建了一个服务,让它们实现一个接口,该接口具有一个 Output() 方法。然后我可以根据用户想要的输出类型将每个服务传递给相同的方法。当客户想要使用 eFax 而不是通过调制解调器发送传真时,只需编写一个实现相同接口的新服务即可。