我刚刚遇到了我认为类型转换的奇怪之处.我有类似以下代码:
interface IMyClass { }
class MyClass: IMyClass { }
class Main
{
void DoSomething(ICollection<IMyClass> theParameter) { }
HashSet<MyClass> FillMyClassSet()
{
//Do stuff
}
void Main()
{
HashSet<MyClass> classSet = FillMyClassSet();
DoSomething(classSet);
}
}
Run Code Online (Sandbox Code Playgroud)
当它到达DoSomething(classSet)时,编译器会抱怨它无法将HashSet <MyClass>强制转换为ICollection <IMyClass>.这是为什么?HashSet实现了ICollection,MyClass实现了IMyClass,那么为什么不能使用强制转换?
顺便说一句,这并不难解决,认为它有点尴尬.
void Main()
{
HashSet<MyClass> classSet = FillMyClassSet();
HashSet<IMyClass> interfaceSet = new HashSet<IMyClass>();
foreach(IMyClass item in classSet)
{
interfaceSet.Add(item);
}
DoSomething(interfaceSet);
}
Run Code Online (Sandbox Code Playgroud)
对我来说,这个作品的事实使得无法施展更加神秘.