WPF C# 中使用 FindName() 获取对象类型及拆箱方法
在 WPF 中,FindName() 方法返回的是一个 object 类型的对象。如果需要确定它的具体类型,可以使用 'is' 运算符或者 'as' 运算符。
使用 'is' 运算符:
object obj = parameter.FindName(strArray[1]);
if (obj is Button)
{
Button btn = (Button)obj; //拆箱
//对btn进行操作
}
使用 'as' 运算符:
object obj = parameter.FindName(strArray[1]);
Button btn = obj as Button;
if (btn != null)
{
//对btn进行操作
}
在拆箱时,需要注意类型转换是否安全,否则会抛出异常。
原文地址: https://www.cveoy.top/t/topic/kf1E 著作权归作者所有。请勿转载和采集!