【发布时间】:2019-07-10 11:51:15
【问题描述】:
在 C# 中,静态类不能从对象以外的任何其他类派生。 目前我有这个基类:
public static class BaseModule
{
public static string UsedSource {get; set;}
public static Write(string text)
{
OtherStaticClass.Log(UsedSource, text);
}
}
现在,根据我使用的类,我想更改UsedSource。
// this does not work
internal static class ModuleA : BaseModule
{
static ModuleA(){
UsedSource = "A" // just an example
}
}
// this does not work
internal static class ModuleB : BaseModule
{
static ModuleB(){
UsedSource = "B" // just an example
}
}
应该这样称呼
ModuleA.Write("Hi");
ModuleB.Write("Hi");
这种方法不起作用,因为静态类不能从对象以外的任何东西派生。 有没有其他方法可以改变属性?
【问题讨论】:
-
如果你想要继承特性,为什么还要使用静态类?
-
如果你同时使用这两个模块会怎样?
-
@TimSchmelter 该类是无状态的,只是“按原样”提供功能。唯一的上下文是
UsedSource。由于调用频繁,我也不想每次都将该参数作为参数传递。 -
@LasseVågsætherKarlsen 两个模块都在不同的项目中,它们不会在同一个程序集中同时被引用。但是,这两个模块都引用了实现基类的核心。
-
这是单例模式的绝佳选择。而是调查一下。
标签: c# inheritance static overriding