[英]Using the `is` operator with Generics in C#
I want to do something like this:我想做这样的事情:
class SomeClass<T>
{
SomeClass()
{
bool IsInterface = T is ISomeInterface;
}
}
What is the best way for something like this?对于这样的事情,最好的方法是什么?
Note: I am not looking to constrain T
with a where
, but I would like my code to be aware of what types of interfaces T
implements.注意:我不希望用where
约束T
,但我希望我的代码知道T
实现的接口类型。 I would prefer that I don't have to construct a T
.我宁愿我不必构造一个T
。
I don't think you can use the is
operator for this.我认为您不能为此使用is
运算符。 But you can use IsAssignableFrom:但是您可以使用 IsAssignableFrom:
bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));
should use following instead应该使用以下代替
bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));
is operator是运算符
is
operator is used to check whether the run-time type
of an object is compatible
with a given type
. is
运算符用于检查对象的run-time type
是否与给定的type
compatible
。
An expression where the use of is
conforms to the syntax, evaluates to true, if both of the following conditions are met:如果满足以下两个条件,则使用is
符合语法的表达式的计算结果为 true:
References参考
You can use IsAssignableFrom :您可以使用IsAssignableFrom :
class SomeClass<T>
{
SomeClass()
{
bool IsIComparable = typeof(IComparable).IsAssignableFrom(typeof(T));
}
}
bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T))
我相信你能做到最好:
bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));
You could try doing something like你可以尝试做类似的事情
Type Ttype = typeof(T);
That will give you the full power of the Type class, which has functions like "FindInterfaces".这将为您提供 Type 类的全部功能,该类具有“FindInterfaces”等功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.