【发布时间】:2011-05-25 16:37:51
【问题描述】:
我有以下代码。我希望它打印出来:
A
B
C
DONE
而是打印
P
P
P
DONE
为什么?
更新
我不是在寻求解决方案。我想知道为什么会这样。我认为泛型是在编译时解决的。据我所知,它应该能够在编译时将这些解析为正确的方法,但显然不是,我不明白为什么。我正在寻找原因的解释,而不是解决方案。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication50
{
class Parent
{
public string FieldName { get; set; }
public string Id { get; set; }
}
class ChildA : Parent
{
public string FieldValue { get; set; }
}
class ChildB : Parent
{
public DateTime? Start { get; set; }
public DateTime? End { get; set; }
}
class ChildC : Parent
{
public ICollection<string> Values { get; set; }
}
class Program
{
void Validate<T>(Parent item) where T : Parent
{
if (item is T)
Validate(item as T);
}
void Validate(ChildA filter)
{
Console.WriteLine("A");
}
void Validate(ChildB filter)
{
Console.WriteLine("B");
}
void Validate(ChildC filter)
{
Console.WriteLine("C");
}
void Validate(Parent filter)
{
Console.WriteLine("P");
// do nothing placeholder so the code will compile
}
ArgumentException Fail(Parent filter, string message)
{
return new ArgumentException(message, filter.FieldName);
}
void Run()
{
var list = new List<Parent> {
new ChildA(), new ChildB(), new ChildC() };
Validate<ChildA>(list[0]);
Validate<ChildB>(list[1]);
Validate<ChildC>(list[2]);
}
public static void Main()
{
new Program().Run();
Console.WriteLine();
Console.WriteLine("DONE");
Console.ReadLine();
}
}
}
【问题讨论】:
-
查看 Eric Lippert blogs.msdn.com/b/ericlippert/archive/2009/07/30/…的这篇博文