你可以在C#中inheritance多少个类?

你可以在.NET中inheritance多少个类?

有几个后端C#文件,我想分享不同的静态方法,但它们都在不同的类中。 有没有办法inheritance多个类?

示例代码将非常感激。

C#不支持多重inheritance(意味着单个类inheritance自多个类)。 但是,您可以在单个类中实现多个接口。

就将inheritance的类链接在一起而言,本身没有限制。 请记住您将为系统引入的复杂性。 使用inheritance时,请确保在“是”方案中使用它。 cheeta是一种动物。 马自达是一辆汽车。 否则,您的inheritance会将您的类与设计变得更加难以维护。

如果它们是静态“实用程序”方法,则只需直接调用它们而不inheritance。 除非这些方法属于您正在创建的实体,否则不应使用inheritance。

您只能从单个类inheritance。 然而,可以实现多个接口。

假设你有Utils.cs:

internal class Utils { public static void Log(string str) { // log str to a file... } } 

并且有一个DB.cs使用Log方法,并在与Utils类相同的命名空间中:

 public class DB { public void SaveToDB() { // some db operations Utils.Log("DB operation successful"); } } 

由于Log方法是静态的,因此您无需初始化Utils类即可使用此方法。

作为结论,您不能使用多重inheritance,但对于您的情况,您不需要这样做。 您可以使用静态方法而无需多重inheritance。

你不能在C#中做多重inheritance。

如果不是因为您想要共享静态方法,则可以使用接口实现相同的目的。

您可以在“链”中inheritance所需的多个类,但.NET语言不允许多重inheritance。

您在.NET中进行多重inheritance的唯一选择是接口。

只要适当地设置了访问器,静态方法或多或少都是共享的(实际上,它们使用VB中的共享关键字); 它们与哪个类没有区别,因为它们与任何实例化对象断开连接。

要调用静态方法,请在其前面加上声明它的类的名称:

 MyClass.MyUtilityMethod(); 

访问者必须是public或者如果调用者和方法在同一个项目/程序集中,它可以是internal的。

如果您的目标仅仅是为静态方法创建单一访问点,则可以创建一个根据需要转发调用的类:

 public static class SharedMethods { public static void SharedMethod1() { ClassA.SharedMethod1(); } public static string GetName() { return NameProvider.GetName(); } public static int GetCount() { return CountClass.GetCount(); } } 

这样您就可以通过SharedMethods.GetName()等访问所有内容。

在.NET中,您只能从一个基类inheritance,但实现多个接口。

对于像您一样的ASP.NET特定情况,您可以执行以下操作:

 public class BasePage : Page { public string SomeMethod() { //Magic happens here } } 

并让您的webformsinheritance自代码隐藏中的BasePage。

另一个经常遵循的方法是创建一个自定义静态类,其中包含所有静态方法。 确保您使用ASP.NET特定的东西为HttpContext.Current添加前缀。

例如:

 public static class HelperClass { public static string GetUsernameFromSession() { return HttpContext.Current.Session["Username"].ToString(); } } 

您不能从多个类inheritance。 但是,您可以将彼此inheritance的类串联起来。

class级员工

class主任:员工

class RegionalDirector:Manager

因此,如果您的程序中有一个完整的命名/员工ID /联系信息方案,您可以从员工inheritance。 然后,详细说明经理的信息,然后为区域主管提供更多信息。