我有一个模型,从 XML 反序列化,其中所有节点对象都派生自同一个基类,并且节点可以任意嵌套(某种程度上)。我正在尝试编写一组模块,这些模块可以将加载的模型转换为各种基于文本的格式。我认为如果每个这样的模块都是一个扩展类,这将允许我简单地调用 Model.ToText()、Model.ToHtml() 等,那就太好了。但我遇到了一些问题。
这是一个简化的示例:
using System;
using System.Collections.Generic;
using System.Text;
namespace Sample
{
public abstract class Foo
{
}
public class Bar : Foo
{
public List<Foo> Children = new List<Foo>();
public int Qux;
}
public class Baz : Foo
{
public string Quux;
}
public static class Extension
{
public static string ToText(this Foo foo, int indent = 0)
{
return String.Format("{0}Foo <>\n", new String(' ', indent));
}
public static string ToText(this Bar bar, int indent=0)
{
StringBuilder sb = new StringBuilder();
sb.Append(String.Format("{0}Bar <Qux={1}>\n", new String(' ', indent), bar.Qux));
foreach (var child in bar.Children)
{
sb.Append(child.ToText(indent + 1));
}
return sb.ToString();
}
public static string ToText(this Baz baz, int indent=0)
{
return String.Format("{0}Baz <Quux={1}>\n", new String(' ', indent), baz.Quux);
}
}
class Program
{
static void Main(string[] args)
{
Baz baz = new Baz { Quux = "frob" };
Bar bar = new Bar
{
Children = new List<Foo>()
{
new Baz {Quux = "fred"},
new Bar
{
Qux = 11,
Children = new List<Foo>()
{
new Baz() {Quux = "flog"}
}
}
}
};
//This works
Console.WriteLine(baz.ToText());
//But this doesn't
Console.WriteLine(bar.ToText());
Console.ReadKey();
}
}
}
如果我运行它,我会得到:
Baz <Quux=frob>
Bar <Qux=0>
Foo <>
Foo <>
如果我尝试变得棘手并这样做:
public static string ToText(this Foo foo, int indent = 0)
{
return ((dynamic)foo).ToText(indent);
}
...第一次打印有效,但第二次给了我例外:
{"'Sample.Baz' does not contain a definition for 'ToText'"}
我可能完全采取了错误的方法,但我可以使用一些方向。