在派生类中定义重载时,C#后期绑定方法重载不起作用
作者:互联网
我需要使用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 void Main(string[] args)
{
List<BaseT> items = new List<BaseT>() {new DerivedA(), new DerivedB()};
var generator = new DerivedGenertor();
generator.Generate(items);
}
}
这是另一个更明显的例子:
class BaseT
{}
class DerivedA : BaseT
{}
class DerivedB : BaseT
{}
class DerivedC : 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 third item
}
}
public virtual string Generate(DerivedA a)
{
return " A ";
}
public virtual string Generate(DerivedC c)
{
return " C ";
}
}
class DerivedGenertor : Generator
{
public virtual string Generate(DerivedB b)
{
return " B ";
}
}
class Program
{
static void Main(string[] args)
{
List<BaseT> items = new List<BaseT>() {new DerivedA(), new DerivedC(), new DerivedB()};
dynamic generator = new DerivedGenertor();
generator.Generate(items);
}
}
解决方法:
您还需要将Generator声明为动态,以便对输入对象和被调用的方法进行动态分辨.但是您必须将访问修饰符更改为public或protected internal才能执行此操作,因为您现在拥有一个外部解析的方法.
class BaseT
{ }
class DerivedA : BaseT
{ }
class DerivedB : BaseT
{ }
class Generator
{
public string Generate(IEnumerable<BaseT> objects)
{
string str = "";
dynamic generator = this;
foreach (dynamic item in objects)
{
str = str + generator.Generate(item);
}
return str;
}
protected internal virtual string Generate(DerivedA a)
{
return " A ";
}
}
class DerivedGenertor : Generator
{
protected internal virtual string Generate(DerivedB b)
{
return " B ";
}
}
class Program
{
static void Main(string[] args)
{
List<BaseT> items = new List<BaseT>() { new DerivedA(), new DerivedB() };
var generator = new DerivedGenertor();
string ret = generator.Generate(items);
}
}
标签:c,dynamic,late-binding 来源: https://codeday.me/bug/20190519/1136740.html