【问题标题】:Derived constructor with type parameter带类型参数的派生构造函数
【发布时间】:2023-03-10 22:14:01
【问题描述】:

编辑:从另一个问题中获得建议的解决方案添加了后续问题 EDIT2:我刚刚意识到不需要我的后续问题。

是否可以让一个类型参数为 T 的抽象基类有一个构造函数,该构造函数接受 T 的参数并将其分配给 T 的属性?我想要实现的是所有派生类都有一个构造函数来做到这一点?

类似:

 public abstract class NotificationBase <T>
{
    public string Text { get; set; }
    public T Context { get; set; }


    public NotificationBase(T context, string text)
    {
        Context = context;
        Text = text;
    }
}

public class NumberNotification : NotificationBase<int>{}

public class Program
{
    public void Run()
    {
        var thing = new NumberNotification(10, "Hello!");

    }
}

编辑: 我得到了另一个问题的链接,该问题解释了如何做到这一点,这很棒。但是我对此有一些问题。我并不是说它错了,如果这是唯一的方法,那就是它。然而,对于我想要做的事情来说,这并不是理想的情况。我解释。这是解决方案:

    public class Base
{
    public Base(Parameter p)
    {
        Init(p)
    }

    void Init(Parameter p)
    {
        // common initialisation code
    }
}

public class Derived : Base
{
    public Derived(Parameter p) : base(p)
    {
 
    }
}

..效果很好。但是,它确实产生了两个小问题,我想看看它们是否可以解决。

  1. 我想要的是强制从基类派生的所有类将 T 传递给构造函数,使其强制。使用此解决方案,可以将其排除在外。
  2. 如果所有类都应该这样做,那么创建构造函数来传播强制参数感觉是多余的。

编辑:我刚刚意识到要求一个传播类型参数的构造函数是我正在寻找的。我确保 T 属性获得一个值,并允许在构造函数中发生其他事情。

【问题讨论】:

  • 这能回答你的问题吗? Can I inherit constructors?
  • @AluanHaddad 是的!但它创造了另一种情况,所以我会更新操作。谢谢!另外:上周所有帖子都立即被否决。那是怎么回事?我看不出我的问题有那么糟糕吗?
  • 什么做什么?我也没有投反对票。
  • @AluanHaddad 哦,不,我不认为你做到了。我只是感到惊讶,似乎有人只是立即对所有内容投反对票。我用我的问题更新了 OP :)

标签: c#


【解决方案1】:

是的,你可以,你只需要使用相关类型传播构造函数链,并在需要时调用祖先:

public class NumberNotification : NotificationBase<int>
{
  public NumberNotification(int context, string text) 
    : base(context, text)
  {
  }
}

如果子类中没有构造函数,您编写的实例将无法编译,因为您没有为编译器提供知道该做什么的方法。

您还可以提供所需的任何其他构造函数。

因此现在可以编译并运行:

var thing = new NumberNotification(10, "Hello!");

Inheritance And Constructors (C# Corner)

base (C# Reference)

【讨论】:

    【解决方案2】:

    NumberNotification 类定义参数化构造函数,该类应该使用base 调用NotificationBase 所需的构造函数

    public class NumberNotification : NotificationBase<int>
    {
        public NumberNotification(int context, string text)
            :base(context, text)
        {
        }
    }
    

    现在对于NumberNotification 对象,上下文是int 的类型,因为这里T 被标记为int 类型,您可以使用以下代码进行检查:

    var thing = new NumberNotification(10, "Hello!");
    Console.WriteLine(thing.Context.GetType());
    

    上面将输出打印为System.Int32

    检查小提琴 - https://dotnetfiddle.net/keufQO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-28
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 2016-07-19
      • 1970-01-01
      • 2021-02-14
      相关资源
      最近更新 更多