确认对象列表属于给定类型?

Confirm that a list of object are of the given types?

我一直在反复尝试确定是否有办法确定 List<> 中的 objects 是否属于特定类型。

基本上我正在尝试开发一个功能

public List<Object> ReadWriteArgs { get; set; }
public Booolean ConfirmRWArgs(int count, List<Type> types)
{
    if(ReadWriteArgs != null && ReadWriteArgs.Count == count)
    {
        // Compare List<Type> to the types of List<Object>
        return true;
    }
    return false;
}

但是根据我所阅读的所有内容和我所尝试的所有内容,我得出的结论是这在 C# 中是不可能的。

编辑:我想在下面进行比较

public Booolean ConfirmRWArgs(int count, List<Type> types)
{
    if(ReadWriteArgs != null && ReadWriteArgs.Count == count)
    {
        if(ReadWriteArgs.Count == types.Count)
        {
            for (int i = 0; i < ReadWriteArgs.Count; i++)
            {
                // Compare the types of the objects in the list ReadWriteArgs
                // to the Types lists in the list types
                //if(ReadWriteArgs[i] is types[i])
                //if(typeof(ReadWriteArgs[i])) == types[i])
            }
            return true;
        }
    }
    return false;
}

是这样的吗?

public List<Object> ReadWriteArgs { get; set; }
public Booolean ConfirmRWArgs(int count, List<Type> types)
{
    if(ReadWriteArgs != null && ReadWriteArgs.Count == count)
    {
        // Compare List<Type> to the types of List<Object>
    if (types.IsGenericType && types.GetGenericTypeDefinition() == typeof(List<>))
        return true;
    }
    return false;
}
public List<Object> ReadWriteArgs { get; set; }
public bool ConfirmRWArgs(int count, List<Type> types)
{
    return ReadWriteArgs != null
           && ReadWriteArgs.Count == count
           && ReadWriteArgs.Zip(types, (arg, type) => arg.GetType() == type).All(b => b);
}

它只是将参数列表和类型列表压缩在一起,检查每个参数的类型是否正确。

测试:

ReadWriteArgs = new List<object>() { "string", 0, 'c' };
ConfirmRWArgs(3, new List<Type>() { typeof(string), typeof(int), typeof(char) }); // true
ConfirmRWArgs(3, new List<Type>() { typeof(string), typeof(int), typeof(bool) }); // false
public List<Object> ReadWriteArgs { get; set; }
public bool ConfirmRWArgs(List<Type> types)
{
    for (int i = 0; i < types.Count; i++)
    {
        if (ReadWriteArgs[i].GetType() != types[i])
            return false;
    }

    return true;
}