简体   繁体   English

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

[英]In C#, how can I design an object that mirrors the SVG protocol

I'm building a very rough implementation of some of the basic SVG elements. 我正在构建一些基本SVG元素的非常粗糙的实现。 I'd like to serialize the object to a usable XML stream. 我想将对象序列化为可用的XML流。 Much of the details I'm OK with, but for some reason, I'm getting stuck on the basics of an type of object ("g) that can contain one or more of the same type of objects. 我可以接受很多细节,但是由于某种原因,我陷入了一种对象(“ g”)的基础问题,该对象可以包含一个或多个相同类型的对象。

Here's a stripped down example: 这是一个简化的示例:

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

The first 'g' element contains other g elements. 第一个“ g”元素包含其他g元素。 What's the best way to design that object? 设计该对象的最佳方法是什么?

[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...

This isn't quite right, or not even close. 这不是很正确,甚至没有结束。 Any ideas? 有任何想法吗?

I'm sorry I don't know C# coupling to XML via XMLTypeOf (from where this come? doesn't show up in MSDN search), but maybe suffice derive from a SVGElement that exposes the common DOM properties, like id,style,... and add the missing declarations: 很抱歉,我不知道C#通过XMLTypeOf耦合到XML(从何而来?在MSDN搜索中未显示),但也许可以从暴露了常见DOM属性(例如id,style, ...并添加缺少的声明:

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 { ... }

Use polymorphism: 使用多态:

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编码生成器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM