代码之家  ›  专栏  ›  技术社区  ›  allanmb

在C#中嵌套的“using”等同于typedef

  •  2
  • allanmb  · 技术社区  · 11 年前

    我有一个类来处理配置文件,我想整理代码,使其更具可读性和可维护性。在C++中,我通常会使用typedefs来完成这项工作,但我发现在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的前提下实现这一点?

    谢谢

    艾伦

    2 回复  |  直到 7 年前
        1
  •  3
  •   Magnus Grindal Bakken    11 年前

    不幸的是,你不能这样做。C/C++中typedef的主要C#替代方案通常是 类型推断 ,例如使用 var 关键字,但在许多情况下仍然必须键入泛型定义。几乎所有的C#程序员都使用Visual Studio或其他IDE,这是有原因的,因为在许多情况下,这些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>
    {
    }
    

    但这当然是小题大做了,除非你还有其他理由想要制作具体的类。

        2
  •  -1
  •   dcastro    11 年前

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