【问题标题】:When the child class inherits the parent class, how can the original type be passed in [duplicate]子类继承父类时,如何传入原来的类型[重复]
【发布时间】:2021-07-06 05:15:18
【问题描述】:
public class Parent<T> where T : class, new()
{
    public class T data { get; set;}
}

public class Child : Parent<decimal>
{
}

错误:类型“decimal”必须是引用类型,才能用作泛型类型或方法“Parent”中的参数“T”

当子类继承父类时,如何传入原来的类型?

【问题讨论】:

  • 你不能在这里传递decimal,因为decimal是一个值类型,你的通用约束明确需要一个引用类型(where T : class)。

标签: c# asp.net-core asp.net-web-api


【解决方案1】:

你的代码有一些错误,把public class T data { get; set;}改成public T data { get; set;}

如果您想在这种情况下使用值类型,请将您的代码更改为:

public class Parent<T> where T: struct
{
   public T data { get; set;}
}

public class Child: Parent<decimal>
{
}

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 2020-02-09
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2023-03-27
    • 2012-04-11
    • 1970-01-01
    相关资源
    最近更新 更多