很难理解要问什么。这是一段代码,解释了您提供的代码片段:
using System;
using System.Collections;
using System.Reflection;
namespace SO14577299
{
class Program
{
static void Main()
{
object result = new Hashtable();
//Trying to get public fields via reflection:
//there are no public fields on this class
FieldInfo[] fields = result.GetType().GetFields();
foreach (FieldInfo fieldInfo in fields)
{
Console.WriteLine("Obj, Field: " + fieldInfo.Name);
}
Console.WriteLine("->1");
Hashtable resultHash = result as Hashtable;
//Trying to list all the keys
//this is an empty collection, nothing there
foreach (string keys in resultHash.Keys)
{
Console.WriteLine("Obj, keys: " + keys);
}
Console.WriteLine("->2");
resultHash = new Hashtable();
resultHash["a"] = "1";
resultHash["b"] = "2";
//Trying to list all the keys
//Now there are two: a and b
foreach (string keys in resultHash.Keys)
{
Console.WriteLine("Obj, keys: " + keys);
}
Console.WriteLine("->3");
}
}
}
这是此代码的输出:
->1
->2
Obj, keys: a
Obj, keys: b
->3
第一个输出是空的,因为您正在尝试枚举 Hashtable 类的公共字段:没有。
第二个输出是空的,仅仅是因为哈希表是空的。如果输出不为空,则第三个输出演示正在打印的内容。
您可以尝试通过输出计数来调试代码:
foreach (string keys in resultHash.Keys)
{
Debug.Log("Count: " + resultHash.Count.ToString());
}
这样你就可以证明/反驳你的哈希表是空的。
也请检查toHashtable
方法。这不是标准方法,您的示例无法说明它可能会做什么。它可以做一些与人们期望的完全不同的事情。如果您知道该对象是哈希表类型,Hashtable resultHash = result as Hashtable
是一个更安全的选择