The usefulness of AS operator in C#
Possible Duplicate:
Direct casting vs 'as' operator?
Where could this operator be useful? Instead of writing this:
Asset a = new Asset();
Stock s = a as Stock; // s is null; no exception thrown
if (s != null) Console.WriteLine (s.SharesOwned);
You'd better write something that throws. I saw tons of
(s != null)
in production code and it really becomes ugly. Exceptions are more descriptive and natural in that way. Even conceptually: how can you get no asset if it is not a stock? It should an exception if it is not a stock.
You'd better write something that throws
Not necessarily. Users don't like seeing things throwing. You should write code that works. And if it doesn't you'd better handle it appropriately by apologizing to the user. The as
operator can be useful in situations where for example you would attempt a cast and if this cast doesn't work assign a default value to the variable so that the code continues to work with this default value. It would really depend on the context.
as
does an is
and if the is
returns false
assigns null
.
sounds like a song but it's the answer and I use it a lot, like in the FindControl methods of ASP.NET:
Button myButton = e.item.FindControl("myControlId") as Button;
this kind of assignment does not crash or throw simply assigns null if FindControl finds something different than a Button. I like this so much....
链接地址: http://www.djcxy.com/p/73738.html上一篇: C#转换选项,除语法之外是否有区别?
下一篇: AS运算符在C#中的用处