首页 新闻 会员 周边

奇怪的泛型问题

0
悬赏园豆:5 [已解决问题] 解决于 2007-12-18 21:36
&nbsp;&nbsp;&nbsp; public class TestClass : ITestInterface<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private string name;<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Name<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; get { return name; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; set { name = value; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp; &nbsp;<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; public interface ITestInterface<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; string Name { get; set;}<br>&nbsp;&nbsp;&nbsp; }<br><br>为什么这样写就不行呢?<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IList&lt;ITestInterface&gt; list = (IList&lt;ITestInterface&gt;)new List&lt;TestClass&gt;();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Assert.IsTrue(list != null);<br><br>我想使用实现相同接口的不同类型的集合类型, 谁能帮帮忙啊~~这些类型又没有实现此接口的公共基类.<br>
问题补充: 谢谢各位, 自己想了一个解, 请大家看看吧.思想跟Klesh Wong的类似. List<ClassA> listA = new List<ClassA>(); for (int i = 0; i < 10; i++) { ClassA a = new ClassA(); listA.Add(a); } List<ClassB> listB = new List<ClassB>(); for (int k = 0; k < 10; k++) { ClassB b = new ClassB(); listB.Add(b); } List<IMyInterface> listInterfaceA = listA.ConvertAll(new Converter<ClassA,IMyInterface>(ConterMyGenericClassA)); Assert.IsTrue(listInterfaceA.Count > 5); List<IMyInterface> listInterfaceB = listB.ConvertAll(new Converter<ClassB, IMyInterface>(ConterMyGenericClassB)); Assert.IsTrue(listInterfaceB.Count > 5); } public static IMyInterface ConterMyGenericClassA(ClassA obj) { return (IMyInterface)obj; } public static IMyInterface ConterMyGenericClassB(ClassB obj) { return (IMyInterface)obj; } 为什么会有这种需求呢, 其实是这样. 通常我们会做一些控件,在里面公开一些数据源的属性,比较 IList<ClassA>, 而这里的数据我们有时候会去视图里面取出来, 如果采用把视图映射成对象的话我们就不能直接把这个源给到控件,当然,也并非不行,比如不使用泛型,就弄个ArrayList也行,但是俺们不是追求完美嘛~~所以这个时候自然就想到抽象一个接口出来使这个控件的数据源不依赖于某个类型,这样我们在做数据访问的时候就省事多了,特别是使用了ORM组件的时候. 再来个泛型加匿名代理的版本,一行就搞定了;) List<IMyInterface> listE = listB.ConvertAll<IMyInterface>(new Converter<ClassB, IMyInterface>(delegate(ClassB b) { return (IMyInterface)b; })); Assert.IsTrue(listE.Count > 0);
沙加的主页 沙加 | 老鸟四级 | 园豆:3680
提问于:2007-12-14 17:48
< >
分享
最佳答案
0
在类型转换的时候,接口转换只针对实现接口的类型 而(IList<ITestInterface>)右侧的List<T>仅仅 [SerializableAttribute] public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable 而这里的T是强类型判断的,此时的T在编译时就已经被指定为TestClass,因此这里不存在一个类型转换的过程。 因此顶多只能(IList<TestClass>)new List<TestClass>(); 而非(IList<ITestInterface>)new List<TestClass>();
volnet(可以叫我大V) | 小虾三级 |园豆:720 | 2007-12-15 03:11
其他回答(1)
0
应该是这样写才比较靠谱: IList<ITestInterface> list = new List<ITestInterface>();
Klesh Wong | 园豆:780 (小虾三级) | 2007-12-14 18:09
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册