c# - 无法将泛型类型转换为 C# 中的列表

标签 c# generics

我正在尝试做一个简单的测试,其中我将两个通用对象传递给一个测试函数,看看它们是否可以转换为 List<S> ,并进一步检查列表的计数是否相等。

以下代码有效:

private static void Test<T> (T obj1, T obj2) {
    if (typeof(T).IsGenericType) {
        var genericTypeParam1 = typeof(T).GetGenericArguments().First();
        Console.WriteLine(genericTypeParam1);

        // LINE MARKER 1
        // var obj1AsList = (obj1 as IEnumerable<genericTypeParam1>);
    }
}

static void Main(string[] args) {
    Test(Enumerable.Range(0, 5).ToList(), Enumerable.Range(0, 5).ToList());
    Console.ReadLine();
}

但是如果我取消注释标有 LINE MARKER 1 的行,我收到以下错误:

The type or namespace name 'genericTypeParam1' could not be found (are you missing a using directive or an assembly reference?)

我事先不知道测试会收到 List秒。但我的意图是首先检查是否 obj1obj2可以作为列表,然后进行比较

var obj1AsList = obj1 as List<genericTypeParam1>;
var obj2AsList = obj2 as List<genericTypeParam1>;
var flag = (obj1AsList != null) && (obj2AsList != null) && (obj1AsList.Count() == obj2AsList.Count());

预先感谢您的帮助。

最佳答案

I am trying to do a simple test, in which I pass in two objects to a test function, see if they can be cast to List<S>, and further, check if the counts of the lists are equal.

正确的做法是:

static bool Test<T>(object obj1, object obj2)
{
    List<T> list1 = obj1 as List<T>;
    List<T> list2 = obj2 as List<T>;
    return list1 != null && list2 != null && list1.Count == list2.Count;
}
...
bool result = Test<int>(Enumerable.Range(0, 5).ToList(), Enumerable.Range(0, 5).ToList());

这需要两个对象和一个类型,如果对象是该类型的大小相等的列表,则返回 true。

关于c# - 无法将泛型类型转换为 C# 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20987073/

相关文章:

c# - 存储和调用通用类型的委托(delegate)

swift - 无法将类型 'T?' 的值转换为预期的参数类型 '_?' - 通用类型和完成 block

Scala 函数/方法参数化返回类型

java - 从 Spring JdbcTemplate 的 queryForObject 方法返回泛型类型

c# - 信号量停止我的线程

C# SQL 聚合 ExecuteScalar 返回查询

c# - 如何将字符串长度转换为像素单位?

javascript - 使用信号器更新数据库更改时如何刷新 View

c# - 在 C# 中究竟什么时候执行事件?

没有指定泛型参数的 Java 类会丢失其方法的类型信息