Ste*_*ane 2 c# generics collections methods casting
我正在写一个通用方法有些麻烦.它有以下签名;
public static ThingCollection<T> GetThings<T>(...) where T : Thing
Run Code Online (Sandbox Code Playgroud)
有几个班级; 从Thing继承的ThingA,ThingB和ThingC; 我希望能够在方法中使用类似的代码.
var things = new ThingCollection<T>();
if (typeof(T) == typeof(Thing))
foreach (var item in someCollection)
things.Add((T)new Thing(...));
else if (typeof(T) == typeof(ThingA))
foreach (var item in someCollection)
things.Add((T)new ThingA(...));
else if (typeof(T) == typeof(ThingB))
foreach (var item in someCollection)
things.Add((T)new ThingB(...));
else if (typeof(T) == typeof(ThingC))
foreach (var item in someCollection)
things.Add((T)new ThingC(...));
else
throw new Exception("Cannot return things of type " + typeof(T).ToString());
return things;
Run Code Online (Sandbox Code Playgroud)
问题是如果我不转换新对象,我得到一个最好的重载方法匹配有无效的参数错误.如上所示添加T强制转换适用于新的Thing(),但报告无法将其他新呼叫的类型'ThingA'转换为'T'.Intellisense表明T是一个东西,但我不明白为什么我不能将其他对象强加给Thing,因为它们继承了它.
也许这不是我正在做的事情的正确方法.我是在正确的轨道上吗?也许缺少一些细微的差别,或者我应该完全做其他事情?
我不知道你要用这个代码做什么.
如果你想创建一个可以添加从Thing派生的任何类型的类的集合,那么ThingCollection不应该有一个Typename:它应该是具体类型的集合.
例如,以这种方式实现A ThingCollection:
public class ThingCollection : List<Thing> {}
Run Code Online (Sandbox Code Playgroud)
现在你可以做到
ThingCollection tc = new ThingCollection();
tc.Add(new ThingA());
tc.Add(new ThingB());
tc.Add(new ThingC());
Run Code Online (Sandbox Code Playgroud)
当然假设ThingA,ThingB和ThingC继承自Thing.
或者您可能希望使用GetThings()过滤派生类型的事物,即您希望调用GetThings()返回ThingCollection.