c# 编码笔记 泛型继承

1 概述

1.1 目标:想做一个泛型的继承,形如下面

A<T>

B<T>:A<T>

1.2. 困惑:结果失败(※1),为说明呢

※1:“T”必须是具有公共的无参数构造函数的非抽象类型,才能用作泛型类型或方法“B<T>”中的参数“T”

1.3 哦明白了,我实际的代码是有约束的。

A<T> where T : new()

B<T>:A<T>

1.4 解决问题,也需要加约束

A<T> where T : new()

B<T>:A<T>where T : new()

2.代码

2.1 有问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 泛型实验2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("test");
            //B<A> b = new B<A>();
            D<A> d = new D<A>();
            Console.ReadKey();
        }
    }
    class A
    {

    }
    abstract class B<T> where T : new()
    {
        T t;
    }
     class C : B<A>
    {

    }
    class D<T>: B<T>

    }
}

2.2 没问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 泛型实验
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("test");
            B<A> b = new B<A>();
            D<A> d = new D<A>();
            Console.ReadKey();
        }
    }
    class A { 
    
    }
    class B<T> {
        T t;
    }
    class C : B<A> { 
        
    }
    class D<T> : B<T> { 
        
    }
}

 2.3 解决问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 泛型实验2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("test");
            //B<A> b = new B<A>();
            D<A> d = new D<A>();
            Console.ReadKey();
        }
    }
    class A
    {

    }
    abstract class B<T> where T : new()
    {
        T t;
    }
     class C : B<A>
    {

    }
    class D<T>: B<T> where T : new()
    {

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值