我有以下代碼。我期待它打印:爲什麼這個通用在編譯時沒有解決?
A
B
C
DONE
,而不是它打印
P
P
P
DONE
爲什麼呢?
UPDATE
我不是要求解決方案。我想知道爲什麼會發生這種情況。我認爲仿製藥在編譯時已經解決了。從我可以告訴它應該能夠在編譯時解決這些適當的方法,但顯然它不是,我不明白爲什麼。我正在尋找解釋原因的解釋,而不是解決方法。
這裏是代碼:
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 http://blogs.msdn.com/b/ericlippert/archive/2009/07/30/generics-are-not-templates.aspx – juharr 2011-05-25 16:50:32