As In C# Example
1 using System;
2
3 class Dog
4 {
5 public void Speak() { Console.WriteLine("Bark!"); }
6 }
7
8 class Example
9 {
10 static void Main()
11 {
12 Object obj = new Dog();
13
14 Dog dog = obj as Dog;
15 if (dog != null)
16 dog.Speak();
17 }
18 }
This example only contains one cast and also allows you to avoid any exceptions that may occur at execution time.
So, the important thing to remember is that if you feel like you need to use is, most likely you ought to use as.
However,
Be careful that you are not using casting to solve a problem that would be better solved with polymorphism. If you find that you are doing multiple checks for different types, casting, and then calling methods on those types, you should reevaluate your approach to see if a polymorphic solution would be better. Casting is a powerful tool but it can be misapplied.
Do'stlaringiz bilan baham: |