Code Bye

泛型方法

为什么本人下面的代码会出错?是不是原因是U没有约束 范围大比where T:B要大,所以不能用A<U> a = new A<U>();     编译器就不通过了?
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace delete2
{
class A<T> where T : B
{
public void liweike<U>()
{ A<U> a = new A<U>(); } //
}
class B
{ }
class C : B
{ }
class Program
{
static void Main(string[] args)
{
}
}
}
假如改成这样就通过了:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace delete2
{
class A<T>
{
public void liweike<U>()
{ A<U> a = new A<U>(); } //
}
class B
{ }
class C : B
{ }
class Program
{
static void Main(string[] args)
{
}
}
}
解决方案

20

引用:
Quote: 引用:

原因是U没约束,而T有约束

能不能讲得再详细点 谢谢

就是你一开始说的

20

你的观点是对的

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明泛型方法