C# 结构字典的自定义别名

C# Custom alias of dictionary of structs

(抱歉,这基本上是我的第一个 C# 程序,我正在翻译 C++)

我这样定义了一个 "user" 结构:

struct user
{
  string usrnm;
  string pw;
}

据说here可以在C#中创建一个伪typedef

namespace _1._0
{
  class Program
  {
    struct user
    {
      string usrnm;
      string pw;
    }
    using (userArr = Dictionary<int, user>);
  }
}

但这行不通;它抛出错误说:

Invalid token 'using' in class, struct or interface member declaration

The type or namespace name 'userArr' could not be found (are you missing a using directive or assembly reference?)

为什么这不起作用,我怎样才能让它起作用?

完整的例子应该是:

using userArr = System.Collections.Generic.Dictionary<int, _1._0.Program.user>;

namespace _1._0
{ 
    // You could place it here, nearly equivalent:
    // using userArr = System.Collections.Generic.Dictionary<int, Program.user>;

    public class Program
    {
        public struct user
        {
            string usrnm;
            string pw;
        }
    }
}

然后在该文件中您可以:

userArr myDictionary = new userArr();

您使用 using 就像 using System;,而不像 using (something) {}。那是另一种类型的 using :),因此您可以将它放在 namespace 声明之外或直接放在 namespace 声明内。不在 class/struct/ 方法体内。请注意,正如 Jeppe 所写,您必须为 Dictionary<>.

使用完整的命名空间

请注意,此 using 将 "work" 仅在您 "used" 它所在的文件中。显然你可以将它重新应用到其他源文件。

但请注意,我同意 CodeCaster。我唯一一次使用 using ... = 是当我在多个命名空间中有相同名称的 类 并且我需要能够区分它们时(例如我有 MyNamespace1.MySubnamespace1.MyClassMyNamespace2.MySubnamespace2.MyClass...我每次都可以写全名或者我可以添加两个 using M1 = MyNamespace1.MySubnamespace1;using M2 = MyNamespace2.MySubnamespace2; 然后 M1.MyClassM2.MyClass)

将 C++ 方法留在 C++ 中。你不需要这些。

只需使用带有属性的 class 并使用正确的语法来实例化字典。

namespace _1._0
{
    public class User
    {
      public string Username { get; set; }
      public string Password { get; set; }      
    }

  class Program
  {
    static void Main(string[] args)
    {
        var userDictionary = new Dictionary<int, User>();
    }
  }
}

我不知道 为什么 你想使用别名,但如果是为了防止多次输入长类型名称,请查看上面使用的 var .

我明白了。来自 C++ 背景,其中所有内容都需要事先声明,我认为我必须对 C# 做同样的事情,但我没有。

using 语句放在 struct user 声明之前效果很好。

(旁注:我从代码中删除了所有此类 "typedefs")