鉴于以下代码,有没有办法可以调用类A的方法X版本?
class A
{
virtual void X() { Console.WriteLine("x"); }
}
class B : A
{
override void X() { Console.WriteLine("y"); }
}
class Program
{
static void Main()
{
A b = new B();
// Call A.X somehow, not B.X...
}
Run Code Online (Sandbox Code Playgroud) 如何使用反射调用被派生类重写的基本方法?
class Base
{
public virtual void Foo() { Console.WriteLine("Base"); }
}
class Derived : Base
{
public override void Foo() { Console.WriteLine("Derived"); }
}
public static void Main()
{
Derived d = new Derived();
typeof(Base).GetMethod("Foo").Invoke(d, null);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
此代码始终显示"派生"...
让我们看一个网格填充的例子。
我们有Column类。它有一个委托FormatCell,它接受一些数据并将其转换为字符串。FormatCell委托在设计时未知 - 它可能由插件设置。
public class ColumnFormatter
{
public Func<Data, string> FormatCell {get; set;}
//...
}
Run Code Online (Sandbox Code Playgroud)
以下是如何使用此类列的示例。
public class Table
{
public List<Column> Columns;
public List<List<string>> BuildTable(List<Data> dataRows)
{
var table = new List<List<string>>();
foreach (var data in dataRows)
{
var line = new List<string>();
foreach (var column in Columns)
{
line.Add(column.FormatCell(data));
}
table.Add(line);
}
return table;
}
}
Run Code Online (Sandbox Code Playgroud)
现在每一列都应该保存它的状态。问题是如何序列化这个 FormatCell 委托?
PS 我知道这个问题,但我的问题更具体。也许有人有针对这种情况的特定可靠的磨合解决方案?