最近和同事们聚在一起的时候聊起了.net面试题。有一个面试题是问GetType()能否被重载。答案是否定的。原因是GetType()不是Virtual的,所以是不能重载的。不让重载GetType()就是为了保证类型安全。我的一个同事突发奇想,说能否用new来重写GetType()方法。如下面的代码:
namespace test
{
public class Employee
{
public new Type GetType()
{
return typeof(string);
}
}
public class Program
{
public static void Main()
{
Employee emp = new Employee();
Console.WriteLine("hello {0}", emp.GetType().Name);
//Object obj = emp;
//Console.WriteLine("obj is System.String = {0}", obj is System.String);
//Console.WriteLine("obj is test.Employee = {0}", obj is test.Employee);
Console.ReadKey();
}
}
}