最近和同事们聚在一起的时候聊起了.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();
}
}
}

相关文章:

  • 2021-11-28
  • 2021-11-28
  • 2021-04-25
猜你喜欢
  • 2021-07-21
  • 2021-06-30
  • 2021-05-18
  • 2021-12-09
  • 2021-08-13
  • 2022-12-23
  • 2021-10-05
相关资源
相似解决方案