C# - 方法签名中的通用类型 - 为什么是 CS1503, "Cannot Convert from IThing to ns.IThing"?

标签 c#

在尝试制定在 Visual Studio 2019 下使用 C# 9 的 EFCore 应用程序使用的适配器模式时,我开发了一种类似于 HandleThing<IThing>(IThing otherThing) 的方法。方法如下

namespace ns {
  public interface IThing
    {

    }

    public class Thing : IThing
    {
        public Thing(IThing thing)
        {
        }
    }

    public class ThingHandler
    {
        public void HandleThing<IThing>(IThing otherThing)
        {
            var entityThing = new Thing(otherThing);
        }
}

随后,我在 HandleThing<IThing> 中遇到错误定义,在 Thing 构造函数的“otherThing”参数处:“CS1503:参数 1:无法从 'ITing' 转换为 'ns.IThing'”。

虽然 VS 建议进行如下所示的强制转换,并且目前看来可行,但我不确定是否理解为什么会发生此错误,或者为什么需要强制转换。


    public class ThingHandler
    {
        public void HandleThing<IThing>(IThing otherThing)
        {
            var entityThing = new Thing((ns.IThing)otherThing);
        }
    }

将其更新为以下内容,还消除了有关可空性的警告


    public class ThingHandler
    {
        public void HandleThing<IThing>(IThing otherThing)
            where IThing: notnull
        {
            var entityThing = new Thing((ns.IThing)otherThing);
        }
    }

我的印象是最初的 IThing 类型 HandleThing<IThing>(IThing otherThing)签名将代表我已经声明的 IThing 接口(interface)类型。

定义中的泛型是否丢失了某些内容?

最佳答案

问题是通用参数不受约束。

您的通用参数声明<IThing>有点倾斜(这可能令人困惑)。使用T ,并且然后Ithing 约束

你拥有什么

public void HandleThing<IThing>(IThing otherThing)

相反,请使用标准 TT前缀,这样你就不会混淆

public class ThingHandler
{
   public void HandleThing<T>(T otherThing) where T : IThing
   {
      var entityThing = new Thing(otherThing);
   }
}

关于C# - 方法签名中的通用类型 - 为什么是 CS1503, "Cannot Convert from IThing to ns.IThing"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65866118/

相关文章:

c# oracle sql 准备语句

c# - 无法使用 C# 读取系统日志

c# - 将 dapper 与 JOIN 一起使用

c# - 如何 - 从进程列表中取消列出我的程序..?

c# - 比较高性能的 int 数组

c# - 无法注册 COM 对象以在计划任务中使用

c# - 带空括号 () 的 Lambda 表达式

c# - WH_MOUSE_LL Hook 不会为注入(inject)的事件(mouse_event、SendInput)调用

c# - 无法通过https访问WCF服务

c# - WPF 更改 ListBox 背景颜色,启用和禁用