泛型方法

weikeli19 2016-10-22 05:33:57
为什么我下面的代码会出错?是不是因为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)
{

}
}
}
...全文
174 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Poopaye 2016-10-24
  • 打赏
  • 举报
回复
不明白为什么你认为是错的。。
weikeli19 2016-10-24
  • 打赏
  • 举报
回复
引用 3 楼 shingoscar 的回复:
[quote=引用 2 楼 weikeli19 的回复:] [quote=引用 1 楼 shingoscar 的回复:] 因为U没约束,而T有约束
能不能讲得再详细点 谢谢[/quote] 就是你一开始说的[/quote] 我表达能力差,就是上次我说的 :还有这个功效啊?把它看成U类型,这是错的! 但是你说了2个概念 其实是第2个概念是对的 就是你的这句话是对的,它里面还牵扯到 树 就是分叉: ∵ U是Animal ∴ 这样调用是合法的:GetSpecies<Chicken>(); ∴ 此时speciesFarm.Animals的类型是List<Chicken>; List<Chicken>.Add不能接收类型是Cow的参数
weikeli19 2016-10-23
  • 打赏
  • 举报
回复
引用 3 楼 shingoscar 的回复:
[quote=引用 2 楼 weikeli19 的回复:] [quote=引用 1 楼 shingoscar 的回复:] 因为U没约束,而T有约束
能不能讲得再详细点 谢谢[/quote] 就是你一开始说的[/quote] 让我脑子整理一下
weikeli19 2016-10-23
  • 打赏
  • 举报
回复
引用 3 楼 shingoscar 的回复:
[quote=引用 2 楼 weikeli19 的回复:] [quote=引用 1 楼 shingoscar 的回复:] 因为U没约束,而T有约束
能不能讲得再详细点 谢谢[/quote] 就是你一开始说的[/quote] singoscar 上次发的帖子 你的理论有问题 我现在一时表达不出 脑子昏昏的
john_QQ:2335298917 2016-10-22
  • 打赏
  • 举报
回复
你的观点是对的
Poopaye 2016-10-22
  • 打赏
  • 举报
回复
引用 2 楼 weikeli19 的回复:
[quote=引用 1 楼 shingoscar 的回复:] 因为U没约束,而T有约束
能不能讲得再详细点 谢谢[/quote] 就是你一开始说的
weikeli19 2016-10-22
  • 打赏
  • 举报
回复
引用 1 楼 shingoscar 的回复:
因为U没约束,而T有约束
能不能讲得再详细点 谢谢
Poopaye 2016-10-22
  • 打赏
  • 举报
回复
因为U没约束,而T有约束

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧