简体   繁体   English

多个约束类型或检查Generic是什么类型的?

[英]Multiple Constraint Types or check what type the Generic is?

I have a Base class that needs a Generic type. 我有一个需要Generic类型的Base类。 That can be either EntityObject or a custom type of mine. 这可以是EntityObject也可以是我的自定义类型。
I need a way to constrain the Base class to EITHER type and I also need a way to check if the Generic is of a certain type. 我需要一种方法将Base类约束为EITHER类型,我还需要一种方法来检查Generic是否属于某种类型。
When I do if (T is EntityObject) or if (typeof(T) is EntityObject) it either says I am using T as a variable, or for typeof(T) I get that it "will never be of the given type". 当我做if (T is EntityObject)或者if (typeof(T) is EntityObject)它或者说我使用T作为变量,或者对于typeof(T)我得到它“永远不会是给定类型”。

You can use: 您可以使用:

if (typeof(T) == typeof(EntityObject))

or 要么

if (typeof(EntityObject).IsAssignableFrom(typeof(T)))

depending on your requirements. 根据您的要求。 (See the docs for Type.IsAssignableFrom for more details.) (有关详细信息,请参阅Type.IsAssignableFrom的文档。)

Of course, this is an execution-time check - you can't have "one of..." constraints at compile time. 当然,这是一个执行时间检查 - 在编译时你不能有“一个......”约束。 Depending on your scenario, it may well be appropriate to have two differently named and constrained public methods which call one unconstrained private method (which "knows" you've got an appropriate type due to only being called from the public ones). 根据您的情况,有两个不同命名和约束的公共方法可能适合调用一个不受约束的私有方法(由于仅从公共方法调用,因此“知道”您有一个合适的类型)。

There is no way to constrain for two unrelated types. 没有办法限制两种不相关的类型。 You either need a common type (like an interface) or two versions of the constrained generic class. 您需要一个公共类型(如接口)或两个版本的受约束泛型类。

Assuming T is unconstrained, you can use if (typeof(T).Equals(typeof(EntityObject))) { ... } to check whether T is of a certain type. 假设T不受约束,您可以使用if (typeof(T).Equals(typeof(EntityObject))) { ... }来检查T是否属于某种类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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