C#数组的有趣现象和一个泛型相关的问题

guoyichao 2011-08-05 04:19:54
var type = typeof(int[][,][,,]);
Console.WriteLine(type.Name);
怎么会打印出了这个?
如果用反射构造这个type
var type = typeof(int).MakeArrayType().MakeArrayType(2).MakeArrayType(3);
这样写得到的Type居然不是typeof(int[][,][,,])……

有一组方法形式都是Func<T, TResult>,通过反射来获取
var type = typeof(Func<,>)
type.MakeGenericMethod(typeof(int), typeof(int)) 将得到形式为Func<int, int>的方法。
type.MakeGenericMethod(typeof(string), typeof(string)) 奖得到形式为Func<string, string>的方法。
那么如果有一组方法形如Func<List<T>, List<TResult>>,怎么通过反射来得到实参方法?
var type = typeof(Func<,>) 不匹配
var type = typeof(Func<List<>,List<>>)无法编译
这种泛型嵌泛型的类型怎么获得其Type?
...全文
191 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
guoyichao 2011-08-08
  • 打赏
  • 举报
回复
是微软的bug还是特意这么设计的?
longbin891012 2011-08-05
  • 打赏
  • 举报
回复
参看:http://blog.csdn.net/xuwenwu/article/details/6646809


var 关键字指示编译器通过查看在 from 子句中指定的数据源来推断查询变量的类型。下面的示例生成与上一个示例相同的编译代码:

var customerQuery2 =
from cust in customers
where cust.City == "London"
select cust;

foreach(var customer in customerQuery2)
{
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}
鸭梨山大帝 2011-08-05
  • 打赏
  • 举报
回复
2楼,跟var无关,表来混淆话题... ...
=========
关于问题一:

楼主试试这个:

     
static void Main(string[] args)
{
System.Int32[][,][, ,] o = new System.Int32[0][,][, ,];
int[][,][, ,] o1 = new int[0][,][, ,];
if (o.GetType() == o1.GetType()) { Console.WriteLine("Yes"); }
if (typeof(System.Int32[][,][, ,]) == o1.GetType()) { Console.WriteLine("Yes"); }

var type0 = typeof(int[][,][, ,]);
var type = Type.GetType("System.Int32[][,][, ,]");
var type1 = typeof(System.Int32[][,][, ,]);
var type2 = typeof(System.Int32).MakeArrayType().MakeArrayType(2).MakeArrayType(3);
Console.WriteLine(type0.Name);
Console.WriteLine(type.Name);
Console.WriteLine(type1.Name);
Console.WriteLine(type2.Name);
Console.ReadKey();
}


你会发觉更加纠结了.

int是System.Int32在C#的别名,那么应该来说结果应该都是 Int32[0][,][, ,].
为什么会这样呢?
个人觉得,微软也不是神,微软程序员也不是神,一行代码都可能有BUG,所以,个人认为这个是个BUG.
心灵彩虹 2011-08-05
  • 打赏
  • 举报
回复
var 关键字指示编译器通过查看在 from 子句中指定的数据源来推断查询变量的类型。下面的示例生成与上一个示例相同的编译代码:

var customerQuery2 =
from cust in customers
where cust.City == "London"
select cust;

foreach(var customer in customerQuery2)
{
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}



当变量的类型明显或显式指定嵌套泛型类型(如由组查询生成的那些类型)并不重要时,var 关键字很有用。通常,我们建议如果您使用 var,应意识到这可能使您的代码更难以让别人理解。
白鸽 2011-08-05
  • 打赏
  • 举报
回复
吐血了!还是顶吧,

110,549

社区成员

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

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

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