gpt4 book ai didi

c# - 覆盖并行类层次结构中的方法

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:07 24 4
gpt4 key购买 nike

我有哪些选项可以解决以下并行继承层次结构的问题?我想让 Serializer 类保持无状态。

public abstract class BaseSerializerOptions
{
public Boolean SortComponents { get; set; }
}

public class TextSerializerOptions : BaseSerializerOptions
{
public Int32 TrimStrings { get; set; }
}

public class BinarySerializerOptions : BaseSerializerOptions
{
public Boolean SkipNulls { get; set; }
}

public abstract class BaseSerializer
{
public abstract void Serialize(Object obj, Stream s, BaseSerializerOptions opt);
}

public class TextSerializer : BaseSerializer
{
public override void Serialize(Object obj, Stream s, TextSerializerOptions opt)
{
}
}

public class BinarySerializer : BaseSerializer
{
public override void Serialize(Object obj, Stream s, BinarySerializerOptions opt)
{
}
}

我希望能够编写这样的方法:

    static void Test(BaseSerializer s, BaseSerializerOptions o)
{
var obj = new MyObject { ... };
using (var f = File.OpenWrite("..."))
{
s.Serialize(obj, f, o);
}
// do more things here to check the serializer result;
// the serializers might return some kind of operation status, which I want to check
}

static void TestSerializers()
{
Test(new TextSerializer(), new TextSerializerOptions {...});
Test(new BinarySerializer(), new BinarySerializerOptions {...});
}

最佳答案

扩展评论中的第一个建议:

public abstract class BaseSerializerOptions
{
public Boolean SortComponents { get; set; }
}

public class TextSerializerOptions : BaseSerializerOptions
{
public Int32 TrimStrings { get; set; }
}

public class BinarySerializerOptions : BaseSerializerOptions
{
public Boolean SkipNulls { get; set; }
}

public abstract class BaseSerializer<T> where T : BaseSerializerOptions
{
public abstract void Serialize(Object obj, Stream s, T opt);
}

public class TextSerializer : BaseSerializer<TextSerializerOptions>
{
public override void Serialize(Object obj, Stream s, TextSerializerOptions opt)
{
}
}

public class BinarySerializer : BaseSerializer<BinarySerializerOptions>
{
public override void Serialize(Object obj, Stream s, BinarySerializerOptions opt)
{
}
}

特定语法用法的更新:

public class TextSerializer : BaseSerializer
{
public void Serialize(Object obj, Stream s, TextSerializerOptions opt)
{
this.Serialize(obj, s, opt);
}

public override void Serialize(object obj, Stream s, BaseSerializerOptions opt)
{
if (opt is TextSerializerOptions options)
{

}
else
{

}
}
}

public class BinarySerializer : BaseSerializer
{
public void Serialize(Object obj, Stream s, BinarySerializerOptions opt)
{
this.Serialize(obj, s, opt);
}

public override void Serialize(object obj, Stream s, BaseSerializerOptions opt)
{
if (opt is BinarySerializerOptions options)
{

}
else
{

}
}
}

关于c# - 覆盖并行类层次结构中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54138312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com