A real use for `as` and `is`

2019-04-19 00:39发布

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?

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?

14条回答
何必那么认真
2楼-- · 2019-04-19 01:16

If you're really never having to do casting then I you likely wouldn't have much use for these operators. In my experience, however, .NET programming calls for a lot of casting particularly when dealing with delegates where arguments are provided typed as 'object'. I think that the introduction of generics has helped cut down on the need for casting, but it's certainly something that I use pretty often. I might be "doing it wrong" but that's just been my experience.

So if you're going to do casting anyway I really like the 'is' operator for improved readability of the code. I'd much rather look at

if(foo is SomeType) {...}

then

if(foo.GetType() == typeof(SomeType)) {...}
查看更多
别忘想泡老子
3楼-- · 2019-04-19 01:17

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.

Marc

查看更多
登录 后发表回答