我遇到了一位前雇员的相当多的类(class)。在检查代码的作用时,我遇到了一个具有 internal static
属性的 struct
。
该结构使用得相当频繁。大多数属性只有 get
,但有些属性确实有 set
和 get
。该结构大约有 200 行长,其中包含嵌套的内部结构。
我无法完全理解这个结构以及这个人想用它实现的目标。
它没有经过测试,也没有文档让我想知道为什么这个人决定实现这样的事情。
该结构主要包含整个程序中使用的设置和路径。
在我重构这段代码并将其称为开发人员的“早期杰作”之前,我想检查一下我是否错了,在非常罕见的情况下使用这样的东西是一个相当合理的想法。
我的问题是: 为什么有人应该使用具有公共(public)静态属性的结构以及有人将如何摆脱它(可能是众所周知的重构或类似的东西),因为它在整个代码中使用(Visual Studio 计算了约 800 个引用)
顺便说一句: 它没有放置在任何命名空间中
internal struct ConfigurationPaths
{
private static string _pathConfig;
private static string _pathConfigUI;
private static string _pathConfigUI_Default;
private static string _pathConfig_DataToView;
//... removed the following lines due to readability in the question
internal static string AppPath
{
get
{
Module[] mod = Assembly.GetExecutingAssembly().GetModules();
return Path.GetDirectoryName(mod[0].FullyQualifiedName);
}
}
internal static string FilePath
{
set { _pathConfig = value; }
get { return _pathConfig; }
}
internal static string UserInterface
{
set { _pathConfigUI = value; }
get { return _pathConfigUI; }
}
internal static string UserInterface_Default
{
get
{
if (_pathConfigUI_Default == null)
{
String appPath = AppPath.AppendPathSeperatorIfNeeded();
_pathConfigUI_Default = String.Format("{0}files{1}config{1}ui{1}default.ux", appPath, Path.DirectorySeparatorChar);
}
return _pathConfigUI_Default;
}
}
internal static string UserInterface_GridView
{
set { _pathConfig_DataToView = value; }
get { return _pathConfig_DataToView; }
}
//... removed the following lines due to readability in the question
}
最佳答案
看起来意图是为了配置。如果是这样的话,静态类会更有用
internal static class Configuration { ... }
struct
这样做没有任何值(value),也不是惯用的。至于他们为什么这样做……可能只是不是最伟大的开发商。我会将配置类放在项目的根命名空间中,尽管他们可能将它放在没有命名空间中以避免在整个代码库中使用一些 using
声明。
如果全局/静态性质困扰您,我建议将整个事物转换为实例属性并将其传递给需要它的事物。这样做,它变得更像是一个配置服务——也许完全删除 setter 并将执行设置的代码内部化。这样肯定会更面向对象。
这也有助于依赖注入(inject)和可测试性,特别是如果您在其上添加一个接口(interface)。
关于c# - 重构具有内部静态属性的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50236282/