例如,我有一些代码逻辑来检查我的通用类型参数是否为类对象之一的特定类型
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
可能永远不适用于通用类型对象?
对于typeof
和GetType
都定义为在运行时获取类型,为什么typeof
有效但此处GetType()
不起作用?
b。反正有第二和第三工作吗?
[您需要使用auto
检查您的is
参数,而不是通用类型参数,因此auto is Ford
应该可用。
此处auto.GetType()
相同。
T
是泛型类型参数,它基本上是客户端指定的特定类型的占位符。您无法像在类型名称上那样调用实例方法,例如int
,string
等。