나는 컴파일 타임에 유형을 알 수없는 객체 목록을 가지고 있습니다.일반 유형의 리플렉션을 사용하여 Count 속성을 얻는 방법
'Count'속성이있는 개체를 식별하고 값이 있으면 그 값을 가져와야합니다.
이 코드는 간단한 컬렉션 유형에 대해 작동합니다
PropertyInfo countProperty = objectValue.GetType().GetProperty("Count");
if (countProperty != null)
{
int count = (int)countProperty.GetValue(objectValue, null);
}
문제는이 같은 IDictionary<TKey,TValue>
로, 일반적인 유형 작동하지 않는다는 것입니다. 이 경우 'Count'속성이 인스턴스화 된 객체에 있어도 'countProperty'값은 null로 반환됩니다.
내가 원하는 것은 컬렉션/사전 기반 개체를 식별하고 크기가있는 개체를 찾으면됩니다.
편집 : 요청에 따라, 여기이 간단한 컬렉션에서 확인을 작동하지만,하지 Dictionary<TKey,TValue>
에서 파생 내가 가진 클래스에서 생성 된 객체에
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;
}
}
작동하지 않는 코드의 전체 목록입니다 . 즉
CustomClass :
Dictionary<TKey,TValue>
CacheItemInfo 캐시 항목에 대한 속성이 포함되어 단순한 클래스입니다 - 즉, 키, 계산, 유형, 만료 날짜
('IDictionary'에 대한 생각은'GetType()'이 항상 * concrete * 타입을 반환 할 것이기 때문에 여기서는 도움이되지 않습니다. 무엇이든 가능하지만'Dictionary '입니다) –
다음 코드는 그것은 여전히 유효하지 않습니다. –
그래서 대답은 반사를 무시하고 인터페이스로 전송하는 것이 었습니다. 아래의 정답을 참조하십시오. –