如何将类型与实例进行比较?
这是我尝试的但是没有编译
继承错误:
错误242类型或命名空间名称'键入'无法找到(是 你错过了使用指令或程序集引用?)
public static Control GetParentControl(this Control c, Type type)
{
Control p = c.Parent;
while (p != null && !(p is type))
{
p = p.Parent;
}
return p;
}
答案 0 :(得分:4)
替换
while (p != null && !(p is type))
与
while (p != null && !(p.GetType() == type))
is
运算符只能与类型名称一起使用,而不能与Type
类型的变量一起使用。您需要在变量上调用GetType
以获取其类型并将其与类型变量进行比较。
答案 1 :(得分:0)
我不得不使用模板。
PreBooking pb = GetParent<PreBooking>.Get(this) as PreBooking;
public class GetParent<T>
{
public static object Get(Control c)
{
Control p = c.Parent;
while (p != null && !(p is T))
{
p = p.Parent;
}
return p;
}
}