C#-在运行时确定通用参数类型时,为什么是is或GetType()不起作用[重复]

问题描述 投票:-1回答:1

例如,我有一些代码逻辑来检查我的通用类型参数是否为类对象之一的特定类型

public Interface ICar {...}

public class Ford : ICar {...}

// method to define if input parameter type is Ford
public bool IsThisAFord(T auto) where T : class, ICar
{
   return typeof(T) == typeof(Ford);
   // return (T is Ford) failed - T is a type, which is not valid in the given context
   // return T.GetType.Equals(Ford) failed - T is a type parameter, which is not valid in the given context
}

a。那么,为什么我的使用is关键字和GetType的第二种方法和第三种方法不能与泛型类型参数一起使用?

  • 对于is可能不起作用,因为我猜想它仅适用于对象类型而不适用于类类型,这是否意味着is可能永远不适用于通用类型对象?

  • 对于typeofGetType都定义为在运行时获取类型,为什么typeof有效但此处GetType()不起作用?

b。反正有第二和第三工作吗?

c# types runtime generic-programming compile-time
1个回答
1
投票
  1. [您需要使用auto检查您的is参数,而不是通用类型参数,因此auto is Ford应该可用。

  2. 此处auto.GetType()相同。

T是泛型类型参数,它基本上是客户端指定的特定类型的占位符。您无法像在类型名称上那样调用实例方法,例如intstring等。

© www.soinside.com 2019 - 2024. All rights reserved.