【发布时间】:2011-01-06 07:05:18
【问题描述】:
我有一个对象列表,在编译时我无法知道其类型。
我需要识别任何存在“计数”属性的对象,如果存在则获取值。
此代码适用于简单的集合类型:
PropertyInfo countProperty = objectValue.GetType().GetProperty("Count");
if (countProperty != null)
{
int count = (int)countProperty.GetValue(objectValue, null);
}
问题在于这不适用于泛型类型,例如IDictionary<TKey,TValue>。在这些情况下,“countProperty”值返回为 null,即使实例对象中存在“Count”属性。
我要做的就是识别任何基于集合/字典的对象并找到它的大小(如果有的话)。
编辑:根据要求,这是不起作用的代码的完整列表
private static void GetCacheCollectionValues(ref CacheItemInfo item, object cacheItemValue)
{
try
{
//look for a count property using reflection
PropertyInfo countProperty = cacheItemValue.GetType().GetProperty("Count");
if (countProperty != null)
{
int count = (int)countProperty.GetValue(cacheItemValue, null);
item.Count = count;
}
else
{
//poke around for a 'values' property
PropertyInfo valuesProperty = cacheItemValue.GetType().GetProperty("Values");
int valuesCount = -1;
if (valuesProperty != null)
{
object values = valuesProperty.GetValue(cacheItemValue, null);
if (values != null)
{
PropertyInfo valuesCountProperty = values.GetType().GetProperty("Count");
if (countProperty != null)
{
valuesCount = (int)valuesCountProperty.GetValue(cacheItemValue, null);
}
}
}
if (valuesCount > -1)
item.Count = valuesCount;
else
item.Count = -1;
}
}
catch (Exception ex)
{
item.Count = -1;
item.Message = "Exception on 'Count':" + ex.Message;
}
}
这适用于简单的集合,但不适用于从我拥有的从Dictionary<TKey,TValue> 派生的类创建的对象。即
CustomClass :
Dictionary<TKey,TValue>
CacheItemInfo 只是一个简单的类,其中包含缓存项的属性 - 即键、计数、类型、到期日期时间
【问题讨论】:
-
(从
IDictionary<TKey,TValue>的角度思考在这里没有帮助,因为GetType()将始终返回 concrete 类型,它可以是任何东西,但很可能是@ 987654328@) -
这是当前的代码 - 仍然无法正常工作。
-
所以答案是忽略反射并只转换到接口 - 请参阅下面的正确答案。
标签: c# reflection