对于`as`和`is`一个真正的使用 [英] A real use for `as` and `is`

查看:104
本文介绍了对于`as`和`is`一个真正的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用-never- 在C#或支持关键字的任何语言。

I have -never- used as or is in C# or any language that supports the keyword.

你有什么用它来做什么?

What have you used it for?

我不意味我如何使用它我的意思是你怎么样真的需要它?

I dont mean how do i use it i mean how have you actually need it?

我也做了客场的没有类型转换在一个相当大的C ++项目(我很自豪)。

I also got away with doing no typecasting in a fairly large c++ project (i was proud).

因此,考虑我几乎从来没有强制类型转换为什么需要关键字

So considering i almost never typecast why do i need the keyword as or is?

推荐答案

我不得不写代码来枚举放置在Web窗体ASP.NET所有控件并在特定的控制,如执行某些操作添加背景颜色到所有文本框,等等。

I had to write code to enumerate over all the controls placed on a ASP.NET webform and perform certain operations on specific controls, e.g. add a background color to all Textboxes, and so on.

的主要优点和对我来说是我可以安全地检查变量是否是使用给定类型是没有异常情况发生。有一次,我敢肯定,这是一个给定类型的,我可以安全,轻松地将其转换为使用所需要的类型。

The main benefit of as and is for me is that I can safely check whether a variable is of a given type using is without exceptions happening. Once I'm sure it's of a given type, I can safely and easily convert it to the type needed using as.

我基本上没(简体!)是一个

What I basically did (simplified!) is a

foreach(Control c in form.Controls)
{
   if(c is Textbox)
      HandleTextbox(c as Textbox);

   if(c is Listbox)
      HandleListbox(c as Listbox);
}



等。如果没有这将是一个很大混乱,恕我直言。

and so on. Without as and is this would be a lot messier, IMHO.

基本上,你可能需要或者可以好好利用如果你处理多态性很多 - 如果你有事情,可以在我的例子在页面上任意数量的类型,如控制列表。如果你没有或者不使用多态很多,你不可能遇到的那些运营商的需求。

Basically, you'll probably need or can make good use of as and is if you're dealing with polymorphism a lot - if you have lists of things that can be any number of types, like controls on a page in my example. If you don't have or don't use polymorphism a lot, you're unlikely to encounter the need for those operators.

马克

这篇关于对于`as`和`is`一个真正的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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