ProgramingTip

주어진 값이 일반 목록인지 어떻게 확인합니까?

bestdevel 2020. 10. 25. 12:44
반응형

주어진 값이 일반 목록인지 어떻게 확인합니까?


public bool IsList(object value)
    {
        Type type = value.GetType();
        // Check if type is a generic list of any type
    }

주어진 개체가 목록인지 또는 목록으로 캐스팅 될 수 있는지 확인하는 가장 좋은 방법은 무엇입니까?


if(value is IList && value.GetType().IsGenericType) {

}

확장 메서드 사용을 즐기는 여러분을 위해 :

public static bool IsGenericList(this object o)
{
    var oType = o.GetType();
    return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>)));
}

따라서 다음과 같이 할 수 있습니다.

if(o.IsGenericList())
{
 //...
}

 bool isList = o.GetType().IsGenericType 
                && o.GetType().GetGenericTypeDefinition() == typeof(IList<>));

public bool IsList(object value) {
    return value is IList 
        || IsGenericList(value);
}

public bool IsGenericList(object value) {
    var type = value.GetType();
    return type.IsGenericType
        && typeof(List<>) == type.GetGenericTypeDefinition();
}

if(value is IList && value.GetType().GetGenericArguments().Length > 0)
{

}

Victor Rodrigues의 답변에 따라 제네릭에 대한 또 다른 방법을 고안 할 수 있습니다. 실제로 원래 솔루션은 두 줄로만 작동 가능합니다.

public static bool IsGenericList(this object Value)
{
    var t = Value.GetType();
    return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>);
}

public static bool IsGenericList<T>(this object Value)
{
    var t = Value.GetType();
    return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<T>);
}


다음은 .NET Standard에서 작동하고 인터페이스에 작동하는 구현입니다.

    public static bool ImplementsGenericInterface(this Type type, Type interfaceType)
    {
        return type
            .GetTypeInfo()
            .ImplementedInterfaces
            .Any(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == interfaceType);
    }

다음은 테스트 (xunit)입니다.

    [Fact]
    public void ImplementsGenericInterface_List_IsValidInterfaceTypes()
    {
        var list = new List<string>();
        Assert.True(list.GetType().ImplementsGenericInterface(typeof(IList<>)));
        Assert.True(list.GetType().ImplementsGenericInterface(typeof(IEnumerable<>)));
        Assert.True(list.GetType().ImplementsGenericInterface(typeof(IReadOnlyList<>)));
    }

    [Fact]
    public void ImplementsGenericInterface_List_IsNotInvalidInterfaceTypes()
    {
        var list = new List<string>();
        Assert.False(list.GetType().ImplementsGenericInterface(typeof(string)));
        Assert.False(list.GetType().ImplementsGenericInterface(typeof(IDictionary<,>)));
        Assert.False(list.GetType().ImplementsGenericInterface(typeof(IComparable<>)));
        Assert.False(list.GetType().ImplementsGenericInterface(typeof(DateTime)));
    }

아마도 가장 좋은 방법은 다음과 같이하는 것입니다.

IList list = value as IList;

if (list != null)
{
    // use list in here
}

이를 통해 최대한의 유연성을 제공하고 IList인터페이스 를 구현하는 다양한 유형으로 작업 할 수 있습니다 .


다음 코드를 사용하고 있습니다.

public bool IsList(Type type) => IsGeneric(type) && (
            (type.GetGenericTypeDefinition() == typeof(List<>))
            || (type.GetGenericTypeDefinition() == typeof(IList<>))
            );

참고 URL : https://stackoverflow.com/questions/794198/how-do-i-check-if-a-given-value-is-a-generic-list

반응형