Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 不带泛型的运行时类型转换_C# - Fatal编程技术网

C# 不带泛型的运行时类型转换

C# 不带泛型的运行时类型转换,c#,C#,这个代码有效。但是注意到第6行和第10行之间的相似性 void someThing_Click(object sender, RoutedEventArgs e) { President pres; if (e.GetType() == typeof(MouseButtonEventArgs)) { pres = (sender as SomeUserControl ).DataContext as President;

这个代码有效。但是注意到第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;

上面的代码不起作用,只是为了说明。

DataContext属性属于类
FrameworkElement
,即您的
SomeUserControl
MenuItem
继承自
FrameworkElement
。因此,您可以直接将其键入cast to
FrameworkElement

pres = ((FrameworkElement)sender).DataContext as President;

我认为不需要检查事件参数的类型,这就足够了

President pres = ((FrameworkElement)sender).DataContext as President;

FrameworkElement

var fe = sender as FrameworkElement
if(fe != null)
{
    President pres = fe.DataContext as President;
}

只有在检查结果时才使用“as”运算符。在其他情况下,您应该使用普通强制转换(类型)运算符—它具有更好的性能。“普通”(直接)强制转换不会更快,在内部它使用[is]和[as]运算符的组合。请看一下我对@xxMUROxx answer的评论。这与OP的代码在语义上不同,您遗漏了其他部分;虽然如果布洛克本身完全是多余的,我猜也没必要,但他两样都能当上总统cases@Sriram-我希望描述中的意图是明确的。任何方法都可以删除else部分。Rohit,这确实很清楚,但是当您使用
if
而不使用else时,如果
e
不是
MouseButtonEventArgs
类型,则代码的语义将发生更改。这就是我的观点。[as]和null比较的组合是使用非类型化对象执行特定类型作业的最有效方法。(直接强制转换首先检查[is],然后抛出异常或返回使用[as]运算符强制转换的对象,这是一个额外的[is]操作)@Andrew point 1同意,但是我不同意直接强制转换首先检查[is],然后抛出异常或返回使用[as]操作符强制转换的对象,这是一个额外的[is]操作你能显示官方文档吗?或者任何可证明的链接?例如:直接转换在内部被转换为
if(variable is T){return(variable as T)}throw我过去做过一些数学(类似于负载测试)尝试做同样的事情:一百万个直接强制转换操作与一百万个[is]-[as]组合另一个好的: