小编Jam*_*esH的帖子

C#Type-casting oddity - 接口作为泛型类型

我刚刚遇到了我认为类型转换的奇怪之处.我有类似以下代码:

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)

对我来说,这个作品的事实使得无法施展更加神秘.

.net c# casting interface

4
推荐指数
1
解决办法
1656
查看次数

标签 统计

.net ×1

c# ×1

casting ×1

interface ×1