目前我在通用类型方面有点挣扎。
在阅读相关内容时,我有时会遇到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
至于闭包参数,这个问题是关于语法的含义的。
由于在MEF中导出泛型类型而引起的混乱,我对此感到困惑
我注意到:
new Dictionary<string,bool>().GetType() == typeof(Dictionary<,>)
false
new Dictionary<string,bool>().GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>)
true
Run Code Online (Sandbox Code Playgroud)
然而,Dictionary <,>本身不被视为'类型',因为这实际上会产生编译错误:
new Dictionary<string,bool> as Dictionary<,>
Type expected
new Dictionary<string,bool> is Dictionary<,>
Type expected
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,Dictionary <,>实际上是一种类型?.NET对泛型类型的处理方式与非泛型类型不同吗?
现在在MEF中我可以导出一个泛型类
[Export(typeof(MyGenericClass<,>))]
Run Code Online (Sandbox Code Playgroud)
这将满足进口要求,如
[Import]
public MyGenericClass<string, long> Instance { get; set; }
Run Code Online (Sandbox Code Playgroud)
我对这里的类型系统规则感到困惑
我尝试使用模板方法(foo1)中的方法(foo2),编译器说他不知道属于那个类(T)的这个方法(foo2).
什么是正确的语法,哪个编译器接受它?
private void foo1<T>(T instance)
{
instance.foo2();
}
Run Code Online (Sandbox Code Playgroud) 我可以通过使用检查单一类型
if (e.PropertyType == typeof(EntityCollection<Search_SearchCodes>))
Run Code Online (Sandbox Code Playgroud)
但我真的想避免所有的对象 EntityCollections
if (e.PropertyType == typeof(EntityCollection))
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
如果我有这个代码:
public interface IThing<T> where T : class
{
// ...
}
public class BaseThing<T> : IThing<T> where T : class
{
// ...
}
public class ThingA : BaseThing<string>
{
// ...
}
public class ThingB : BaseThing<Uri>
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
此代码失败:
List<IThing<object>> thingList = new List<IThing<object>>();
thingList.Add(new ThingA());
thingList.Add(new ThingB());
Run Code Online (Sandbox Code Playgroud)
即使ThingA(间接)继承自(并且应该是其实例)IThing<T>.为什么?是ThingA/ ThingB不是IThing<T>?