使用typeof对象转换类型为(表达式为type) [英] convert type with (expression as type) with typeof object
本文介绍了使用typeof对象转换类型为(表达式为type)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过用户控件中的代码删除用户控件的用户控件
,然后如果父亲是StackPanel我使用:
Hi,
I want to remove user control from it's parent by code inside the user control
,then if the parent is StackPanel i use:
(this.Parent as StackPanel).Children.Remove(this);
但是父母不仅仅用于StackPanel,所以我必须将as的转换类型设为动态,使用此代码
but the parent is not for StackPanel only, so i have to make type of conversion of "as" to be dynamic, by using this code
Type parentType = this.Parent.GetType();
(this.Parent as parentType ).Children.Remove(this);
但这是错误:
but this is error :
Error 15 The type or namespace name 'parentType' could not be found (are you missing a using directive or an assembly reference?)
所以,是关闭/处置/删除用户控件的代码自己的任何解决方案吗?
谢谢。
so, is it any solution to close/dispose/remove the usercontrol from it's code self?
Thank you.
推荐答案
StackPanel panel = this.Parent as StackPanel;
if (panel != null) {
panel.Children.Remove(this);
}
应该这样做。
should do it.
鉴于您的层次结构,您必须编写转换运算符。
查看以下示例代码:
第1类:
公共课obj1
{
公共字符串a;
public void test1()
{
}
}
Class 2:
公共课obj2
{
公共字符串b;
public void test2()
{
}
public static explicit operator obj2(obj1 b)
{
返回新的obj2
{
b = ba
};
}
}
转换:
obj1 o1 =新obj1();
o1.a =new_tex t;
obj2 o2 =(obj2)o1; //将obj1类型的对象转换为obj2
检查您是否能够对此进行类型转换.Parentto ParentType
Given your hierarchy, you will have to write a conversion operator.
check below sample code:
Class 1:
public class obj1
{
public string a;
public void test1()
{
}
}
Class 2:
public class obj2
{
public string b;
public void test2()
{
}
public static explicit operator obj2(obj1 b)
{
return new obj2
{
b = b.a
};
}
}
CONVERSION:
obj1 o1 = new obj1();
o1.a = "new_text";
obj2 o2 = (obj2)o1; //converting object of type obj1 to obj2
Check if you are able to typecast "this.Parent" to ParentType
这篇关于使用typeof对象转换类型为(表达式为type)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文