我有一个类来处理配置文件,我想整理代码以使其更具可读性和可维护性。在 C++ 中,我通常会使用 typedef 来执行此操作,但我发现在 C# 中可以通过使用 'using' 关键字来执行此操作(请参阅 Equivalent of typedef in C# )。我唯一的问题是似乎没有办法嵌套它们。这是我想要实现的目标:
using ConfigValue = System.Collections.Generic.List< System.String >;
using ConfigKey = System.String;
using ConfigSection = System.Collections.Generic.Dictionary< ConfigKey, ConfigValue >;
如果我更改 ConfigKey 或 ConfigValue 的类型并忘记更改 ConfigSection,如何在不显式 ConfigSection 的情况下实现此目的?
谢谢
艾伦
最佳答案
不幸的是,你不能这样做。 C/C++ 中 typedef 的主要 C# 替代方案通常是类型推断,例如使用 var
关键字,但在许多情况下您仍然需要输入通用定义。几乎所有 C# 程序员都使用 Visual Studio 或其他 IDE,这在许多情况下使他们无需输入所有内容,这是有原因的。
我其实不太推荐“using-as-typedef”模式,因为我预计大多数 C# 程序员会对它感到陌生和惊讶。另外,我认为您必须在每个文件中包含“psuedo-typedef”这一事实大大降低了它的实用性。
您可以考虑做的一件事当然是从您想要 typedef 的内容中创建实际的类,例如像这样:
public class ConfigValue : List<string>
{
}
public class ConfigKey
{
private string s;
public ConfigKey(string s)
{
this.s = s;
}
// The implicit operators will allow you to write stuff like:
// ConfigKey c = "test";
// string s = c;
public static implicit operator string(ConfigKey c)
{
return c.s;
}
public static implicit operator ConfigKey(string s)
{
return new ConfigKey(s);
}
}
public class ConfigSection : Dictionary<ConfigKey, ConfigValue>
{
}
但这当然是多余的,除非您还有其他原因想要创建具体的类。
关于c# - 在 C# 中嵌套 'using' 相当于 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18570457/