简体   繁体   English

在 C# 中使用带有泛型的 `is` 运算符

[英]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:

  • expression is not null.表达式不为空。
  • expression can be cast to type.表达式可以强制转换为类型。 That is, a cast expression of the form (type)(expression) will complete without throwing an exception.也就是说,形式为 (type)(expression) 的强制转换表达式将完成而不会引发异常。 For more information, see 7.6.6 Cast expressions.有关详细信息,请参阅7.6.6 Cast 表达式。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM