开关外壳上键入c# [英] Switch case on type c#

查看:221
本文介绍了开关外壳上键入c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/298976/c-sharp-is-there-a-better-alternative-than-this-to-switch-on-type">C# - 是否有比这更好的选择的类型转换'

您好想我得到一个大的if / else在类的类型。这是有办法带开关的情况下做到这一点?

例如:

 功能测试(obj对象)
{
如果(obj是WebControl的)
{

}否则,如果(obj为文本框)
{

}
否则,如果(obj为组合框)
{

}
 

等等...

我想创造的东西像

 开关(OBJ)
{
案例是文本框:
打破;
情况是组合框:
打破;

}
 

}

解决方案

没有。

<一个href="http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx">http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx

  

我们得到了很多的请求的addditions到C#语言和今天   我要谈的比较常见者之一 - 上式开关。   开启式看起来像pretty的有效和直接的特性:   添加一个类似开关的结构,它接通的类型   前pression,而不是值。这可能看起来像   这样的:

 开关的typeof(五){
        案例INT:...突破;
        案例字符串:...突破;
        案例双:...突破;
        默认:...突破;
}
 

  

这样的说法将是增加虚拟非常有用   像派遣了一个不相交的类型层次结构,或者在一个类型的方法   你不拥有包含层次结构类型。见此状的例子   这一点,你可以很容易地得出结论,该功能会   简单的和有用的。它甚至可以让你想:为什么不   这些#*&放大器;%$懒C#语言的设计者只是让我的生活更轻松,   加入这个简单,省时的语言特性?

     

不幸的是,像许多简单的语言特性,类型开关   因为它第一次出现并不是那么简单。烦恼,当你在开始   更显著,以及同样重要的,这样的例子:

Possible Duplicate:
C# - Is there a better alternative than this to 'switch on type'?

Hello suppose i get a big if/else on class type. it's there a way to do it with a switch case ?

Example :

function test(object obj)
{
if(obj is WebControl)
{

}else if(obj is TextBox)
{

}
else if(obj is ComboBox)
{

}

etc ...

I would like to create something like

switch(obj)
{
case is TextBox:
break;
case is ComboBox:
break;

}

}

解决方案

No.

http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx

We get a lot of requests for addditions to the C# language and today I'm going to talk about one of the more common ones - switch on type. Switch on type looks like a pretty useful and straightforward feature: Add a switch-like construct which switches on the type of the expression, rather than the value. This might look something like this:

switch typeof(e) { 
        case int:    ... break; 
        case string: ... break; 
        case double: ... break; 
        default:     ... break; 
}

This kind of statement would be extremely useful for adding virtual method like dispatch over a disjoint type hierarchy, or over a type hierarchy containing types that you don't own. Seeing an example like this, you could easily conclude that the feature would be straightforward and useful. It might even get you thinking "Why don't those #*&%$ lazy C# language designers just make my life easier and add this simple, timesaving language feature?"

Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:

这篇关于开关外壳上键入c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆