当 class 被密封时,类型 ... 的表达式无法由模式处理

An expression of type ... cannot be handled by a pattern when class is sealed

我收到一个相当奇怪的错误:

CS8121 An expression of type 'IGrouping<string, IMyInterface>' cannot be handled by a pattern of type 'MyClass1'.

线路发生错误:

if(tGroup is MyClass1 myclass1)

但未密封的MyClass2没有报错

  1. 这是什么原因造成的?
  2. 除了不密封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)
        {
        }
    }
}