作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试做一个简单的测试,其中我将两个通用对象传递给一个测试函数,看看它们是否可以转换为 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
秒。但我的意图是首先检查是否 obj1
和 obj2
可以作为列表,然后进行比较
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/
我是一名优秀的程序员,十分优秀!