從C++背景來看,我遇到了基於泛型類型的特定實例重載的障礙。以下情況不起作用,因爲只有一次Foo<T>
類的代碼實例已生成,因此在Method
內部,this
的類型僅爲Foo<T>
,而不是Foo<A>
或Foo<B>
,正如我所希望的那樣。在C++中,我習慣於將實例化爲獨特類型的模板。如何通過泛型類型的特定實例重載C#方法
using System.Collections.Generic;
class A
{
// Concrete class
}
class B
{
// Concrete class
}
class Bar
{
public void OverloadedMethod(Foo<A> a) {} // do some A related stuff
public void OverloadedMethod(Foo<B> b) {} // do some B related stuff
public void OverloadedMethod(OtherFoo of) {} // do some other stuff
public void VisitFoo(FooBase fb) { fb.Method(this); }
}
abstract class FooBase
{
public abstract void Method(Bar b);
}
class Foo<T> : FooBase
{
// Class that deals with As and Bs in an identical fashion.
public override void Method(Bar b)
{
// Doesn't compile here
b.OverloadedMethod(this);
}
}
class OtherFoo : FooBase
{
public override void Method(Bar b)
{
b.OverloadedMethod(this);
}
}
class Program
{
static void Main(string[] args)
{
List<FooBase> ListOfFoos = new List<FooBase>();
ListOfFoos.Add(new OtherFoo());
ListOfFoos.Add(new Foo<A>());
ListOfFoos.Add(new Foo<B>());
Bar b = new Bar();
foreach (FooBase fb in ListOfFoos)
b.VisitFoo(fb);
// Hopefully call each of the Bar::Overloaded methods
}
}
有沒有辦法讓這樣的東西在C#中工作?我寧願不必將Foo中的代碼複製爲我想用於其中的每種類型的單獨的類。
編輯: 希望這是一個更清晰一點。
你能澄清嗎?你是否需要它接受一個具有特定類型的泛型類的實例?即MyGenericClass? –
BenAlabaster
2009-01-01 20:22:53
你期望被稱爲哪個超載? – JaredPar 2009-01-01 20:23:38
你的例子不清楚,因爲像「foo 」 - 是A和B的實際類型?完成示例(即我們可以編譯並獲取您感興趣的錯誤)將會有很大幫助。 – 2009-01-01 20:24:29