C# 3.0:在集合中填充具有不同行为的对象
我想填充组合框中的项目,每个项目都有不同的行为。 是的,我知道我可以简单地创建 3 个从基类派生的类。 但我的问题是“还有其他方法吗”和“什么是可能的”。 在 Java 中,我们可以执行“new MyClass(){public void overriddenmethod(){...} }”,但在 C# 中我们不能,不是吗?
现在我使用 lambda 动态定义一个方法,但问题是我稍后想要 new XxxFormatter() 作为该对象的实例变量。 由于 XxxFormatters 不共享公共基类,因此我无法将它们作为 SerializingHelper 类中的单个字段。
你有什么想法?
public delegate void SerializingHandler(Stream s, object o);
class SerializingHelper
{
public string Name { get; set; }
public SerializingHandler Serializer { get; set; }
}
comboFormat.Items.AddRange(new object[]
{
new SerializingHelper{ Name = "Binary",
Serializer = (s,o)=>new BinaryFormatter().Serialize(s,o),
new SerializingHelper{ Name = "Soap",
Serializer = (s,o)=>new SoapFormatter().Serialize(s,o),
new SerializingHelper{ Name = "Xml",
Serializer = (s,o)=>new XmlSerializer(typeof(KontaktpartnerData), new Type[]
{typeof(ArrayList), typeof(KontaktPartner)}).Serialize(s,o), }
});
I want to fill items in a combobox, each of them has different behaviour.
Yes I know I could simply create 3 classes deriving from a base class. But my question is kind of "is there another way" and "what is possible".
In Java one can do "new MyClass(){public void overriddenmethod(){...} }" but in C# we can not, can we?
Now I use a lambda to define a method on the fly but the problem is that I later want the new XxxFormatter() as instance variable of that object. Since the XxxFormatters share no common base class I cannot put them as a single field in the SerializingHelper class.
Do you have any Ideas?
public delegate void SerializingHandler(Stream s, object o);
class SerializingHelper
{
public string Name { get; set; }
public SerializingHandler Serializer { get; set; }
}
comboFormat.Items.AddRange(new object[]
{
new SerializingHelper{ Name = "Binary",
Serializer = (s,o)=>new BinaryFormatter().Serialize(s,o),
new SerializingHelper{ Name = "Soap",
Serializer = (s,o)=>new SoapFormatter().Serialize(s,o),
new SerializingHelper{ Name = "Xml",
Serializer = (s,o)=>new XmlSerializer(typeof(KontaktpartnerData), new Type[]
{typeof(ArrayList), typeof(KontaktPartner)}).Serialize(s,o), }
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只是想防止每次实例化新的序列化程序实例,您可以在 lambda 之外实例化它们:
如果您确实需要将格式化程序存储为字段,您可以执行以下操作:
If you just want to prevent instantiating a new serializer instance each time, you can instantiate them outside of the lambda:
If you really need to store the formatter as a field, you could do something like this: