나는 동적으로 다음 클래스의 속성의 유형에 따라 일반 사전을 만들려고 오전 :클래스의 속성 유형을 기반으로 C# generic 사전을 동적으로 만드는 방법은 무엇입니까?
public class StatsModel
{
public Dictionary<string, int> Stats { get; set; }
}
하는의이 속성은 변수 'propertyType'에와 있다는 할당 된 통계의 System.Type을 가정 해 봅시다 형식이 일반 사전 인 경우 IsGenericDictionary 메서드는 True를 반환합니다. 나는 동적으로 동일한 유형의 일반적인 사전 인스턴스를 생성 Activator.CreateInstance로를 사용
이미 생성 된 객체가 나는 유형이 일반 사전에 캐스팅하고 싶은 일반 사전이 있음을 알고 있기 때문에// Note: property is a System.Reflection.PropertyInfo
Type propertyType = property.PropertyType;
if (IsGenericDictionary(propertyType))
{
object dictionary = Activator.CreateInstance(propertyType);
}
인수는 속성 유형의 일반적인 인수와 동일합니다.
Type[] genericArguments = propertyType.GetGenericArguments();
// genericArguments contains two Types: System.String and System.Int32
Dictionary<?, ?> = (Dictionary<?, ?>)Activator.CreateInstance(propertyType);
가능합니까?
액세스 내가 찾던 것입니다. 나는 해킹을 좋아하지 않기 때문에 특히 IDictionary로 캐스팅 할 것이다 ;-) 대단히 감사합니다. Marc! – Jeroen
다음과 같이 표시됩니다. generic 형식 'System.Collections.Generic.IDictionary'에 2 개의 형식 인수가 필요합니다. –
tdc
@tdc 코드 파일 맨 위에'using System.Collections;'지시문을 추가하십시오. –