source

C#일반목록T타입취득방법

ittop 2023. 4. 17. 22:30
반응형

C#일반목록T타입취득방법

지금 성찰 프로젝트를 하고 있는데 꼼짝도 못하고 있어요.

의 목적이 있다면myclass를 지탱할 수 있는List<SomeClass>아래 코드와 같은 타입을 취득하는 방법을 아는 사람이 있습니까?myclass.SomList비어있나요?

List<myclass> myList = dataGenerator.getMyClasses();
lbxObjects.ItemsSource = myList; 
lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;

private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Reflect();
}

Private void Reflect()
{
    foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())
    {
        switch (pi.PropertyType.Name.ToLower())
        {
            case "list`1":
            {           
                // This works if the List<T> contains one or more elements.
                Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));

                // but how is it possible to get the Type if the value is null? 
                // I need to be able to create a new object of the type the generic list expect. 
                // Type type = pi.getType?? // how to get the Type of the class inside List<T>?
                break;
            }
        }
    }
}

private Type GetGenericType(object obj)
{
    if (obj != null)
    {
        Type t = obj.GetType();
        if (t.IsGenericType)
        {
            Type[] at = t.GetGenericArguments();
            t = at.First<Type>();
        } 
        return t;
    }
    else
    {
        return null;
    }
}
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

보다 일반적으로는, 모든 것을 서포트합니다.IList<T>인터페이스를 체크할 필요가 있습니다.

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

내가 의심하는 어떤 물체가 주어진다면IList<>, 그것이 무엇인지를 판별하려면 어떻게 해야 합니까?IList<>?

여기 배짱있는 해결책이 있다.테스트하는 실제 오브젝트가 있는 것을 전제로 하고 있습니다.Type).

public static Type ListOfWhat(Object list)
{
    return ListOfWhat2((dynamic)list);
}

private static Type ListOfWhat2<T>(IList<T> list)
{
    return typeof(T);
}

사용 예:

object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();

인쇄물

typeof(DateTime)

Marc의 답변은 제가 사용하는 접근 방식입니다. 그러나 단순성을 위해(그리고 보다 친근한 API) 다음과 같은 속성을 컬렉션 기본 클래스에서 정의할 수 있습니다.

public abstract class CollectionBase<T> : IList<T>
{
   ...

   public Type ElementType
   {
      get
      {
         return typeof(T);
      }
   }
}

이 접근방식은 유용하며 제네릭스를 처음 접하는 사람이라면 이해하기 쉽습니다.

내가 의심하는 어떤 물체가 주어진다면IList<>, 그것이 무엇인지를 판별하려면 어떻게 해야 합니까?IList<>?

여기 신뢰할 수 있는 솔루션이 있습니다.길어서 죄송합니다.C#의 자기성찰 API는 이 작업을 매우 어렵게 만듭니다.

/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

사용 예:

    object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();

돌아온다

True
typeof(Int32)

언급URL : https://stackoverflow.com/questions/1043755/c-sharp-generic-list-t-how-to-get-the-type-of-t

반응형