不带泛型的运行时类型转换
本文关键字:运行时 类型转换 泛型 | 更新日期: 2023-09-27 17:57:41
此代码有效。但注意到第6和;第10行,
void someThing_Click(object sender, RoutedEventArgs e)
{
President pres;
if (e.GetType() == typeof(MouseButtonEventArgs))
{
pres = (sender as SomeUserControl ).DataContext as President;
}
else
{
pres = (sender as MenuItem ).DataContext as President;
}
}
有没有像这样缩短代码的方法
Type t = (e.GetType() == typeof(MouseButtonEventArgs)) ? SomeUserControl : MenuItem;
pres = (sender as t).DataContext as President;
上面的代码不起作用,只是为了举例说明。
我认为不需要检查事件参数的类型,这应该足够了
President pres = ((FrameworkElement)sender).DataContext as President;
从FrameworkElement
直接使用DataContext
var fe = sender as FrameworkElement
if(fe != null)
{
President pres = fe.DataContext as President;
}
DataContext属性属于FrameworkElement
类,即SomeUserControl
和MenuItem
继承自FrameworkElement
。因此,您可以直接将其转换为FrameworkElement
:
pres = ((FrameworkElement)sender).DataContext as President;