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()
{
}
}