可以使用 `is` 进行类型检查,而不需要知道使用的泛型吗?

huangapple go评论75阅读模式
英文:

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&lt;string&gt; list = new List&lt;string&gt;();

		if (list is List&lt;object&gt;)
			Console.WriteLine(&quot;Success&quot;);
		else
			Console.WriteLine(&quot;Failure&quot;);
    }
}

outputs failure even though string inherits from object. How can I make this program recognise that list is of type List&lt;T&gt; without knowing what T is?

答案1

得分: 2

你可以使用GetGenericTypeDefinition()方法来从List&lt;T&gt;中移除泛型T,得到List&lt;&gt;类型(注意没有T和空的&lt;&gt;),然后进行比较:

if (list.GetType().GetGenericTypeDefinition() == typeof(List&lt;&gt;))
  Console.WriteLine("成功");
else
  Console.WriteLine("失败");

Fiddle

英文:

You can do it with a help of GetGenericTypeDefinition() method to strip generic T from List&lt;T&gt; and have List&lt;&gt; type (note abscence of T and empty &lt;&gt;) to compare with:

if (list.GetType().GetGenericTypeDefinition() == typeof(List&lt;&gt;))
  Console.WriteLine(&quot;Success&quot;);
else
  Console.WriteLine(&quot;Failure&quot;);

Fiddle

答案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(&quot;Success&quot;);
else
    Console.WriteLine(&quot;Failure&quot;);

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) ...

huangapple
  • 本文由 发表于 2023年5月13日 17:01:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定