目前我在通用类型方面有点挣扎。
在阅读相关内容时,我有时会遇到ISomeType<>。
例如:
Type generic = typeof(Dictionary<,>);
Run Code Online (Sandbox Code Playgroud)
https://msdn.microsoft.com/en-us/library/system.type.makegenerictype%28v=vs.110%29.aspx
我真的找不到任何关于空<>方法的文档。
那么:我什么时候应该使用<>or <,>?
更新:
正如 @dcastro 所说,它被称为开放泛型,更多信息可以在这里找到:泛型 - 开放和封闭构造类型
更新2
至于闭包参数,这个问题是关于语法的含义的。
程序集可以在同一命名空间内定义多个具有相同名称的类型,只要每种类型的类型参数(泛型参数)数量不同。尝试例如:
var strA = typeof(Action).ToString(); // "System.Action"
var strB = typeof(Action<>).ToString(); // "System.Action`1[T]"
var strC = typeof(Action<,>).ToString(); // "System.Action`2[T1,T2]"
var strD = typeof(Action<,,>).ToString(); // "System.Action`3[T1,T2,T3]"
Run Code Online (Sandbox Code Playgroud)
在C# 中,只能使用empty <...>,即避免在关键字内指定参数的类型typeof(...)。
另一个例子:typeof(Dictionary<,>).ToString()给出"System.Collections.Generic.Dictionary`2[TKey,TValue]". 正如您所看到的,在 .NET(CLI)中,通用参数的数量是通过附加反引号后跟数字来给出的。
使用示例:
static bool IsDictionary(object obj)
{
if (obj == null)
return false;
var t = obj.GetType();
return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);
}
static object GetDictionary(object a, object b)
{
var t = typeof(Dictionary<,>).MakeGenericType(a.GetType(), b.GetType());
return Activator.CreateInstance(t);
}
Run Code Online (Sandbox Code Playgroud)
但如果可能的话,请避免反射并使用编译时类型,例如(与上面的不太等同):
static Dictionary<TA, TB> GetDictionary<TA, TB>(TA a, TB b)
{
return new Dictionary<TA, TB>();
}
Run Code Online (Sandbox Code Playgroud)