C#在类之间共享代码

mso*_*son 5 c# share

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

继承不是解决方案,因为类已经具有有意义的层次结构.

是否有一些简洁的功能,就像一个C包含文件,让你在其他类中的任何地方插入代码?

编辑:

好吧,我想我们需要一个具体的例子......

该领域有数百个类,经过深思熟虑的类heirarchy.现在,许多这些类需要打印.有一个实用程序打印机类来处理打印.假设有3种不同的打印方法依赖于正在打印的类.调用print方法的代码(6行)是我试图避免在所有不同的客户端类页面上复制和粘贴的代码.

如果人们不会认为他们对操作领域有更多了解,那将是很好的 - 特别是当他们特别提到不合适的技术时......

Eri*_* J. 7

如果您在代表非常不同的东西的类中经常使用的功能,根据我的经验,这应该只属于几个类别:

  • 实用程序(例如字符串格式化,解析,......)
  • 跨领域的关注点(日志记录,安全执法......)

对于实用程序类型的功能,您应该考虑创建单独的类,并在业务类中需要的地方引用实用程序类.

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

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

对于日志记录或安全性等跨领域问题,我建议您研究面向方面编程.

关于其他评论中讨论的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);
   }
}
Run Code Online (Sandbox Code Playgroud)


Kha*_*zor 6

您不能像在 C 中那样通过预处理器指令加载您希望添加到 C# 类中的代码。

但是,您可以定义一个接口并为该接口声明扩展方法。然后您的类可以实现该接口,您可以调用这些类的扩展方法。例如

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

这将允许您重用功能,但您无法访问类的私有成员,就像您可以(例如,散列包含文件)那样。

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