我收到一个相当奇怪的错误:
CS8121 An expression of type 'IGrouping<string, IMyInterface>' cannot be handled by a pattern of type 'MyClass1'.
错误发生在线路上:
if(tGroup is MyClass1 myclass1)
但是,MyClass2
没有报错没有密封。
- 是什么原因造成的?
- 除了不密封
MyClass1
有哪些解决方案?
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
class Program
{
static void Main()
{
IEnumerable<IMyInterface> myInterfaces = new List<IMyInterface>();
foreach (IGrouping<String, IMyInterface> tGroup in myInterfaces.GroupBy(x => x.XXX))
{
if(tGroup is MyClass1 myclass1)
{
}
if(tGroup is MyClass2 myClass2)
{
}
}
}
}
public interface IMyInterface
{
String XXX { get; }
}
public sealed class MyClass1 : IMyInterface
{
public String XXX { get; }
}
public class MyClass2 : IMyInterface
{
public String XXX { get; }
}
}
最佳答案
如果MyClass是密封的,那么永远不会有子类继承MyClass
并实现 IGrouping<string, IMyInterface>
编译器足够聪明,可以推断出这一点,因此会“提示”。
如果没有密封,可能会是这样的:
class WhatEver : MyClass, IGrouping<string, IMyInterface> { ... }
所以编译不能排除is
将永远成功。
编辑 我相信,您真正想要做的是这样的:
foreach (IGrouping<String, IMyInterface> tGroup in myInterfaces.GroupBy(x => x.XXX))
{
foreach(IMyInterface item in tGroup)
{
if(item is MyClass1 myclass1)
{
}
if(item is MyClass2 myClass2)
{
}
}
}
关于c# - 当类被密封时,类型的表达式...不能由模式处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64892676/