在 "using" 上缩写泛型的对象定义

On "using" to abbreviate object definitions of generic type

我是 C# 的新手,所以如果之前有人问过这个问题,我深表歉意,但我已经进行了一些搜索,但没有找到我要找的东西。

具体来说,我知道我可以通过以下方式使用关键字 using 来(以某种方式)模仿 typedef 的使用:

using myStringDict = System.Collections.Generic.Dictionary<string, string>;

或其他预定义类型。

我很想知道是否有办法用泛型来做到这一点。如

using mySomethingDict<T,K> = System.Collections.Generic.Dictionary<T,K>; //this doesn't work

这一切都是为了避免在我的文件中包含 using System.Collections.Generic;(因为我的项目中有很多文件)。

也欢迎其他建议。

不可以,使用别名不能包含类型参数。来自规范:

9.4.1 使用别名指令

Using aliases can name a closed constructed type, but cannot name an unbound generic type declaration without supplying type arguments. For example:

namespace N1
{
    class A<T>
    {
        class B {}
    }
}
namespace N2
{
    using W = N1.A;         // Error, cannot name unbound generic type
    using X = N1.A.B;           // Error, cannot name unbound generic type
    using Y = N1.A<int>;        // Ok, can name closed constructed type
    using Z<T> = N1.A<T>;   // Error, using alias cannot have type parameters
}

您误用了 using 语句。此语句的含义取决于其上下文。在您的情况下,您参考 "using alias directive" 来定义名称空间或类型的别名。然而,这通常用于避免歧义,例如当您定义了自己的 class Math 但还想在代码中使用 System.Math-class 时。因此,为了能够引用这两种类型,您可以使用 using 作为别名,例如using MyMath = MyNamespace.Math

所以 using 不是 typedef 的 C# 等价物。

另一方面,在您的代码中多次使用绝对没问题,它只是显示您的代码使用的 classes。你根本不应该为此烦恼。与您在问题中的陈述相反,您 不是 导入完整的名称空间。您只需加载要在代码中使用的 classes。您可以通过不使用任何 using 并始终对所有类型使用 fully-qualified 名称来做同样的事情,例如System.Generics.Dictionary。这将编译为完全相同的代码,但更难读写。

这与 JAVA 导入类型的方式不同 - 这可能是您混淆的原因。在 JAVA 中,您可以编写 import MyNameSpace.* 来加载命名空间 MyNameSpace 中的 all classes。然而在 C# 中没有这样的东西,你只是指 单一类型 .

See also the examples on the alias