如何检查泛型参数是否为特定类型?

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

How do I check if a generic parameter is of a specific type?

问题

我可以做到这一点

private static void Execute<T>(IList<T> points, ...) where T : Point2D
{
    if (typeof(T) == typeof(Point3D)) // 仅限 Point3D
    {

但我想检查 Point3D 和所有派生类型,类似于:

private static void Execute<T>(IList<T> points, ...) where T : Point2D
{
    if (T is Point3D) // Point3D 及其派生类型
    {

但我得到:错误 CS0119:“T”是一种类型,在给定的上下文中无效

Point3D 类继承自 Point2D。有办法实现这个吗?

英文:

I can do this

private static void Execute<T>(IList<T> points, ...) where T : Point2D
{
    if (typeof(T) == typeof(Point3D)) // Point3D only
    {

but I would like to check against Point3D and all derived types, something like:

private static void Execute<T>(IList<T> points, ...) where T : Point2D
{
    if (T is Point3D) // Point3D ans derived types
    {

but I get: Error CS0119: 'T' is a type, which is not valid in the given context

Point3D class inherits from Point2D one.

Is there any way to accomplish this?

答案1

得分: 3

你可以使用 Type.IsAssignableTo/Type.IsAssignableFrom 中的一个:

IsAssignableTo - 确定当前类型是否可以分配给指定目标类型的变量。

IsAssignableFrom - 确定是否可以将指定类型 c 的实例分配给当前类型的变量。

if (typeof(T).IsAssignableTo(typeof(Point3D)))

请注意,IsAssignableTo 是在 .NET 5 中引入的,因此对于较早的框架版本,您需要使用“reverse”:

if (typeof(Point3D).IsAssignableFrom(typeof(T)))
英文:

You can use one of the Type.IsAssignableTo/Type.IsAssignableFrom :

> IsAssignableTo - Determines whether the current type can be assigned to a variable of the specified targetType.

> IsAssignableFrom - Determines whether an instance of a specified type c can be assigned to a variable of the current type.

if(typeof(T).IsAssignableTo(typeof(Point3D)))

Note that IsAssignableTo was introduced in .NET 5, so for earlier framework version you need to use the "reverse":

if(typeof(Point3D).IsAssignableFrom(typeof(T)))

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

发表评论

匿名网友

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

确定