【发布时间】:2011-02-23 14:15:33
【问题描述】:
我正在尝试制作一个用于调试的非常基本的通用对象打印机,灵感来自于 LinqPad 的出色表现。
以下是我的打印功能的伪代码。我的反射-foo 目前有点弱,我正在努力处理对象是 ILookup 的情况,因为我想枚举查找,将每个键与其关联的集合一起打印。
ILookup 没有非通用接口,也没有实现 IDictionary,所以我现在有点卡住了,因为我不能说 o as ILookup<object,object>... 就此而言,我想知道如何深入研究任何通用接口...假设我想为CustomObject<,,> 提供一个特例。
void Print(object o)
{
if(o == null || o.GetType().IsValueType || o is string)
{
Console.WriteLine(o ?? "*nil*");
return;
}
var dict = o as IDictionary;
if(dict != null)
{
foreach(var key in (o as IDictionary).Keys)
{
var value = dict[key];
Print(key + " " + value);
}
return;
}
//how can i make it work with an ILookup?
//?????????
var coll = o as IEnumerable;
if(coll != null)
{
foreach(var item in coll)
{ print(item); }
return;
}
//else it's some object, reflect the properties+values
{
//reflectiony stuff
}
}
【问题讨论】:
-
这也可能更容易使用多态性,即
void Print(IDictionary dict)、void Print(IEnumerable ienum)、void Print(object o)等。 -
@mellamokb - 我也这么认为。也许我做错了,但相互递归的
Print调用的行为与您预期的不同。 -
根据@xanatos,
ILookup是IEnumerable的IEnumerable。看起来您当前的代码应该按原样工作。如果传入ILookup类型的对象会发生什么? -
@Kobi:我发现我还必须添加
void Print(string s)才能正常工作。 -
作为说明,我删除了我的回复,因为我“发现”对象是否为 ILookup 的方式是错误的(我只检查了 Lookup 实现)。 IEnumerable 的 IEnumerable 是真的并且可以工作,但他会“丢失”“关键”部分。 IEnumerable的IEnumerable只会给他值部分。
标签: c# reflection