C# 中的嵌套'using'等效于 typedef



我有一个类来处理配置文件,我想整理代码,使其更具可读性和可维护性。在C++中,我通常会使用typedef来完成这项工作,但我发现在C#中有一种方法可以通过使用关键字"using"来完成这一工作(请参阅C#中typedef的等价物)。我唯一的问题是似乎没有办法安置这些。以下是我想要实现的目标:

using ConfigValue = System.Collections.Generic.List< System.String >;
using ConfigKey = System.String;
using ConfigSection = System.Collections.Generic.Dictionary< ConfigKey, ConfigValue >;

在更改ConfigKey或ConfigValue的类型并忘记更改ConfigSection的情况下,如何在不显式配置节的情况下实现这一点?

感谢

Allan

不幸的是,您无法做到这一点。C/C++中typedef的主要C#替代方案通常是类型推理,例如使用var关键字,但在许多情况下仍然必须键入泛型定义。几乎所有的C#程序员都使用Visual Studio或其他IDE,这是有原因的,因为在许多情况下,它们可以避免键入所有内容。

我真的不会太推荐"作为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>
{
}

但这当然是过分的,除非你也有其他理由想要制作具体的类。

您不能,并且using x = y不应该用于创建类型别名。它应该用于创建名称空间别名,以解决冲突(例如,名称空间和类共享相同的名称)。

最新更新