在 C# 中,如何设计镜像 SVG 协议的对象

本文关键字:SVG 镜像 协议 对象 | 更新日期: 2023-09-27 18:36:19

我正在构建一些基本SVG元素的非常粗略的实现。我想将对象序列化为可用的 XML 流。很多细节我都可以接受,但由于某种原因,我卡在一种可以包含一个或多个相同类型对象的对象("g")的基础知识上。

下面是一个精简的示例:

<svg>
  <g display="inline">
    <g display="inline">
        <circle id="myCircle1"/>
        <rectangle id="myRectangle1"/>
    </g>
    <circle id="myCircle2"/>
    <rectangle id="myRectangle2"/>
  </g>
</svg>

第一个"g"元素包含其他 g 元素。设计该对象的最佳方式是什么?

[XMLTypeOf("svg")]
public class SVG
{
    public GraphicGroup g {set; get;}
}
public GraphicGroup
{
   public GraphicGroup g {set; get;}
   public Circle circle { set; get;}
   public Rectangle rectangle { set; get;}
}
public Circle...
public Rectangle...

这不太对,甚至不接近。有什么想法吗?

在 C# 中,如何设计镜像 SVG 协议的对象

很抱歉,我不知道通过

XMLTypeOf与XML的C#耦合(这是从哪里来的?没有出现在MSDN搜索中),但也许足以从公开常见DOM属性(如id,style)的SVGElement派生出来,...并添加缺少的声明:

public class SVGElement
{
  public String id {set; get;}
  public String style {set; get;}
}
[XMLTypeOf("svg")]
public class SVG : public SVGElement
{
    public GraphicGroup g {set; get;}
}
[XMLTypeOf("g")]
public class GraphicGroup : public SVGElement
{
   public GraphicGroup g {set; get;}
   public Circle circle { set; get;}
   public Rectangle rectangle { set; get;}
}
[XMLTypeOf("circle")]
public class Circle : public SVGElement { ... }
[XMLTypeOf("rectangle")]
public class Rectangle : public SVGElement { ... }

使用多态性:

public interface IGraphic
{
    void Draw();
}
public class SVG
{
    public GraphicGroup GraphicGroup { get; set; }
}
public class GraphicGroup : IGraphic
{
    public GraphicGroup(Collection<IGraphic> graphics)
    {
        this.Graphics = graphics;
    }
    public Collection<IGraphic> Graphics { get; private set; }
    public void Draw()
    {
        Console.WriteLine("Drawing Graphic Group");
        foreach (IGraphic graphic in this.Graphics)
        {
            graphic.Draw();
        }
    }
}
public class Circle : IGraphic
{
    public void Draw()
    {
        Console.WriteLine("Drawing Circle");
    }
}
使用 XSD

和 XSD 对生成器进行编码