英文:
Is it possible to type check using `is` without knowing the generic used?
问题
"是否可以检查一个变量是否属于使用泛型的特定类型,而不知道该泛型是什么?例如,下面的代码
using System;
using System.Collections.Generic;
public static class Program {
public static void Main(string[] args) {
List<string> list = new List<string>();
if (list is List<object>)
Console.WriteLine("Success");
else
Console.WriteLine("Failure");
}
}
输出"failure",尽管"string"继承自"object"。如何使该程序识别出"list"是"List<T>"类型,而不知道"T"是什么?"
英文:
Is it possible to check if a variable is of a specific type that uses a generic, without knowing what that generic is? For example, the code
using System;
using System.Collections.Generic;
public static class Program {
public static void Main(string[] args) {
List<string> list = new List<string>();
if (list is List<object>)
Console.WriteLine("Success");
else
Console.WriteLine("Failure");
}
}
outputs failure
even though string
inherits from object
. How can I make this program recognise that list
is of type List<T>
without knowing what T
is?
答案1
得分: 2
你可以使用GetGenericTypeDefinition()方法来从List<T>
中移除泛型T
,得到List<>
类型(注意没有T
和空的<>
),然后进行比较:
if (list.GetType().GetGenericTypeDefinition() == typeof(List<>))
Console.WriteLine("成功");
else
Console.WriteLine("失败");
英文:
You can do it with a help of GetGenericTypeDefinition() method to strip generic T
from List<T>
and have List<>
type (note abscence of T
and empty <>
) to compare with:
if (list.GetType().GetGenericTypeDefinition() == typeof(List<>))
Console.WriteLine("Success");
else
Console.WriteLine("Failure");
答案2
得分: 2
你可以测试非泛型接口 IList
:
if (list is IList)
Console.WriteLine("Success");
else
Console.WriteLine("Failure");
请注意,这也适用于数组。因此,使用模式匹配进行测试:
if (list is IList{ IsReadOnly: false }) ...
你可以同时将结果赋给一个新变量:
if (maybeList is IList{ IsReadOnly: false } list) ...
英文:
You can test for the non-generic interface IList
:
if (list is IList)
Console.WriteLine("Success");
else
Console.WriteLine("Failure");
Note that this also succeds for arrays. Therefore test with (using pattern matching):
if (list is IList{ IsReadOnly: false }) ...
You can assign the result to a new variable at the same time:
if (maybeList is IList{ IsReadOnly: false } list) ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论