如何继承泛型类

本文关键字:泛型类 继承 何继承 | 更新日期: 2023-09-27 18:12:42

在c#上工作。我想继承泛型类为此目的,我写了下面的语法

 public class Father
    {
        public string FatherName { get; set; }
    }
    public class Mother
    {
        public string MotherName { get; set; }
    }
    public class Ancestors<T, U> 
    {
        //public class Bar
        //{
        //    private T t;
        //    private U u;
        //}
    }

    class Program : Ancestors<Father, Mother>
    {
        static void Main(string[] args)
        {
            Ansestors.Father.FatherName = "xxx";
        }
    }

我想要anseors . father . fathername = "xxx";属性。我的语法有问题吗?请展示一些语法来解决这个问题。如果有任何疑问请问。提前感谢

如何继承泛型类

看起来你还没有完全理解泛型类的概念。

你用上面的声明对编译器说的是:当你在Program类的代码中发现T(或U)时,将其替换为Father(或Mother)。

为什么你期望Program类有一个Father类型的嵌套对象?它没有在任何地方声明,你所声明的只是一个用于编译器的类型解析指令。

HTH !

class Program
{
    static void Main(string[] args)
    {
        //original parents
        Father father = new Father("George");
        Mother mother = new Mother("Mary");
        //mothers parents aka grandparents
        mother.Mother = new Mother("Ana");
        mother.Father = new Father("Jack");
    }
}
abstract class Ancestor
{
    public String Name { get; set; }
}
public class Father : Ancestor {
    public Mother Mother { get; set; }
    public Father Father { get; set; }
    public Father(String name)
    {
        base.Name = name;
    }
}
public class Mother : Ancestor {
    public Mother Mother { get; set; }
    public Father Father { get; set; }
    public Mother(String name)
    {
        base.Name = name;
    }
}

将公共属性放在Ancestor类中,而将特定属性放在Mother或Father类中。我不明白你为什么需要泛型。

  1. 你不应该继承程序类,这是一个应用程序的入口点
  2. 只是创建一个Ansestors<T, U>类的实例,我稍微修改了祖先类,见下面:
public interface IAncestor
{
    string Name { get; set; }
}
public sealed class Father : IAncestor
{
}
public sealed class Mother : IAncestor
{
}
public sealed class ParentsAncestor<T, U> 
 where T: IAncestor
 where U: IAncestor
{
     public ParentsAncestor(T father, U mother)
     {
         this.Father = father;
         this.Mother = mother;
     }
     public T Father { get; private set; }
     public U Mother { get; private set; } 
}
static void Main(string[] args)
{
     var instance = new ParentsAncestor<Father, Mother>(new Father(), new Mother());
     instance.Father.Name = "The father name";
}