我需要使用c#late binding features在运行时根据对象的类型调用方法重载.当所有重载都在调用发生的同一个类中定义时,它工作正常.但是当在派生类中定义重载时,它不会在运行时绑定.
class BaseT
{}
class DerivedA : BaseT
{}
class DerivedB : BaseT
{}
class Generator
{
public void Generate(IEnumerable<BaseT> objects)
{
string str = "";
foreach (dynamic item in objects)
{
str = str + this.Generate(item); //throws an exception on second item
}
}
protected virtual string Generate(DerivedA a)
{
return " A ";
}
}
class DerivedGenertor : Generator
{
protected virtual string Generate(DerivedB b)
{
return " B ";
}
}
class Program
{
static …Run Code Online (Sandbox Code Playgroud)