MonoGame XML IntermediateSerializer接口和初始化器

时间:2018-03-27 23:33:56

标签: c# xml monogame

我很难弄清楚如何命名和解释我的问题,所以如果这令人困惑,我很抱歉。

我希望能够使用实现接口的类来创建该接口的实例。但是,该接口不(并且不应该,因为它对实现/扩展它的类可能没用)包含某个属性。但是,对于那个类来做它的实际工作,我需要它能够正确地“记住”或者至少在它已经转换为接口之前初始化它。

好吧,我正在尝试做的简化代码:

示例代码:

public class DoStuff {
    public class DoStuffMethod() {
        //not sure if using an interface actually works, haven't tested that yet. 
        //I could probably just use another class and have the classes that were implementing IStuff extend such class instead. Although, not sure if that casts as well...
        IStuff stuff = Content.Load<IStuff>("Stuff");
        stuff.Initialize();
    }
}

public interface IStuff {
    int SomeInt { get; };

    void Initialize();
}

public class StuffClass : IStuff {
    public int SomeInt { get; private set; }
    public int SomeOtherInt { get; private set; }

    public void Initialize() {
        SomeInt += SomeOtherInt;
    }
}

示例Stuff.xml(作为Stuff.xnb):

<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
  <Asset Type="StuffClass">
    <!-- Numbers have no significance, just random ones -->
    <SomeInt>1</SomeInt>
    <SomeOtherInt>4</SomeOtherInt>
  </Asset>
</XnaContent>

1 个答案:

答案 0 :(得分:0)

这样的事情应该是有效的。

var obj = Content.Load<object>("your_xml_content_xnb");
if (obj is IStuff)
{
   (obj as IStuff).Initialize();
}