class Person{// A Person should be able to Feed// another Entity, but they way he feeds// each is differentpublic override void Feed( Entity e ){if( e is Person ){// feed me}else if( e is Animal ){// ruff}}}
而是
class Person{public override void Feed( Person p ){// feed the person}public override void Feed( Animal a ){// feed the animal}}
class Animal { }class Dog : Animal { }
void PrintTypes(Animal a) {Console.WriteLine(a.GetType() == typeof(Animal)); // falseConsole.WriteLine(a is Animal); // trueConsole.WriteLine(a.GetType() == typeof(Dog)); // trueConsole.WriteLine(a is Dog); // true}
Dog spot = new Dog();PrintTypes(spot);
typeof(T)呢?它也在编译时解决吗?
是的。T总是表达式的类型。记住,泛型方法基本上是一大堆具有适当类型的方法。例子:
string Foo<T>(T parameter) { return typeof(T).Name; }
Animal probably_a_dog = new Dog();Dog definitely_a_dog = new Dog();
Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"Foo<Animal>(probably_a_dog); // this is exactly the same as aboveFoo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.
Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"Foo<Dog>(definitely_a_dog); // this is exactly the same as above.Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal".Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"
class Animal{}class Dog : Animal{}
static void Foo(){object o = new Dog();
if(o.GetType() == typeof(Animal))Console.WriteLine("o is an animal");Console.WriteLine("o is something else");}
这将打印"o is something else",因为o的类型是Dog,而不是Animal。但是,如果您使用Type类的IsAssignableFrom方法,您可以使此工作。
if(typeof(Animal).IsAssignableFrom(o.GetType())) // note use of tested typeConsole.WriteLine("o is an animal");
Button button = obj1 as Button;if (button != null){// do stuff...return;}TextBox text = obj1 as TextBox;if (text != null){// do stuff...return;}Label label = obj1 as Label;if (label != null){// do stuff...return;}// ... and so on