检查类型是浇注料/小类 [英] Check if types are castable / subclasses
问题描述
我有他们作为字符串输入两名成员 - 而不是一个类型的实例。我如何检查两种类型浇注料?比方说串的一个是System.Windows.Forms.Label,另一种是System.Windows.Forms.Control的。如何检查,如果第一个是第二个的子类(或隐式浇注料)?这是可能通过使用反射?
I have they type of two members as strings - and not as a Type instance. How can I check if the two types are castable? Let's say string one is "System.Windows.Forms.Label" and the other one is "System.Windows.Forms.Control". How can I check if the first one is a subclass (or implicit castable) of the second one? Is this possible by using reflection?
感谢您的支持!
推荐答案
这似乎是你应该使用 Type.IsAssignableFrom
但要注意仔细的文档:
It might seem like you should use Type.IsAssignableFrom
but note carefully the documentation:
公共虚拟布尔IsAssignableFrom(C型)
真正
如果ç
和电流[实例] 键入
表示相同的类型,或者如果当前[实例] 键入
是的继承层次ç
,或者如果电流[实例] 键入
是一个接口 C
工具,或者如果 C
是一个泛型类型参数和当前[实例] 键入
表示的ç
之一。 假
如果这些条件都不是真正
,或 C
是空
引用(没有
在Visual Basic中)。
true
if c
and the current [instance of] Type
represent the same type, or if the current [instance of] Type
is in the inheritance hierarchy of c
, or if the current [instance of] Type
is an interface that c
implements, or if c
is a generic type parameter and the current [instance of] Type
represents one of the constraints of c
. false
if none of these conditions are true
, or if c
is a null
reference (Nothing
in Visual Basic).
在特定的:
class Base { }
clase NotABase { public static implicit operator Base(NotABase o) { // } }
Console.WriteLine(typeof(Base).IsAssignableFrom(typeof(NotABase)));
将打印假
在控制台上,即使 NotABase
是隐式强制转换为基本
秒。因此,要处理铸造,我们可以使用反射像这样:
will print False
on the console even though NotABase
s are implicitly castable to Base
s. So, to handle casting, we could use reflection like so:
static class TypeExtensions {
public static bool IsCastableTo(this Type from, Type to) {
if (to.IsAssignableFrom(from)) {
return true;
}
var methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(
m => m.ReturnType == to &&
(m.Name == "op_Implicit" ||
m.Name == "op_Explicit")
);
return methods.Count() > 0;
}
}
用法:
Usage:
Console.WriteLine(typeof(string).IsCastableTo(typeof(int))); // false
Console.WriteLine(typeof(NotABase).IsCastableTo(typeof(Base))); // true
和你的情况下
// from is string representing type name, e.g. "System.Windows.Forms.Label"
// to is string representing type name, e.g. "System.Windows.Forms.Control"
Type fromType = Type.GetType(from);
Type toType = Type.GetType(to);
bool castable = from.IsCastableTo(to);
这篇关于检查类型是浇注料/小类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!