c# - 当类被密封时,类型的表达式...不能由模式处理

标签 c# compiler-errors

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

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)
        {
        }
    }
}

关于c# - 当类被密封时,类型的表达式...不能由模式处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64892676/

相关文章:

c# - 如何使用 wpf 应用程序在 Twitter 上共享数据或消息?

c# - Auto Patcher(高效的自动更新程序)

c# - 发布/订阅架构

c++ - "Error: no operator for cin>>"我可以 't figure out what I' m 在这里做错了

c++ - 加密货币在编译时出现错误

java - 编译错误 : Cannot Find Symbol

java - 构建 jenetics 库时出现命令行错误

c# - 禁用 Windows 窗体上的退出按钮?

c# - 带有 Xamarin 的 Android Things IGpioCallback 问题

c - 函数返回局部变量的地址,但仍在c中编译,为什么?