Java和x27之间的差异;s可序列化和C#&x27;ISerializable
我正在把一些Java代码翻译成C。Java代码看起来像Java和x27之间的差异;s可序列化和C#&x27;ISerializable,c#,java,serialization,translation,clone,C#,Java,Serialization,Translation,Clone,我正在把一些Java代码翻译成C。Java代码看起来像 public abstract class myClass implements Cloneable, Serializable { //fields, constructors etc here. //... //... public abstract Object clone(); //an implementation of this is eventually provided in a subclass //... //.
public abstract class myClass implements Cloneable, Serializable {
//fields, constructors etc here.
//...
//...
public abstract Object clone(); //an implementation of this is eventually provided
in a subclass
//...
//...
}
Cloneable接口中的clone()已实现,Serializable没有任何方法,因此不需要从那里实现任何内容
在C#中,我的班级看起来像这样:
public class myClass : ISerializable, ICloneable{
//fields, constructors etc here.
//...
//...
public abstract Object Clone ();
//...
//...
[Serializable]
public class myClass : ICloneable
{
//fields, constructors etc here.
//...
//...
public abstract Object Clone ();
//...
//...
}
}
如您所见,ICloneable的方法已经实现,但在C#中,与Java的可序列化不同,ISerializable接口确实有一个方法,所以我需要实现它。问题是我不确定如何翻译,因为我是从Java翻译这段代码,而这不需要在那里完成
有人能告诉我怎么用C#做这个吗
我知道缺少的方法是GetObjectData,但我不知道如何实现它,传递给它什么,或者应该在它内部包含什么,因为Java等价物中完全没有这个方法…我假设您已经使用Java中的
Serializable
接口来通知您的类可以序列化。在.Net中,您应该使用[Serializable]
属性,因为ISerializable
接口有点不同的含义
因此,在.Net中,您的代码应该如下所示:
public class myClass : ISerializable, ICloneable{
//fields, constructors etc here.
//...
//...
public abstract Object Clone ();
//...
//...
[Serializable]
public class myClass : ICloneable
{
//fields, constructors etc here.
//...
//...
public abstract Object Clone ();
//...
//...
}
我假设您已经使用Java中的
Serializable
接口通知您的类可以序列化。在.Net中,您应该使用[Serializable]
属性,因为ISerializable
接口有点不同的含义
因此,在.Net中,您的代码应该如下所示:
public class myClass : ISerializable, ICloneable{
//fields, constructors etc here.
//...
//...
public abstract Object Clone ();
//...
//...
[Serializable]
public class myClass : ICloneable
{
//fields, constructors etc here.
//...
//...
public abstract Object Clone ();
//...
//...
}
在Java中,声明类“implements Serializable”将该类标记为“Serializable”。Java接口是标记 在C#中,您可以通过使用.Net“Serializable”属性标记类来实现等效:
// A test object that needs to be serialized.
[Serializable()]
public class TestSimpleObject {
public int member1;
public string member2;
public string member3;
public double member4;
// A field that is not serialized.
[NonSerialized()] public string member5;
public TestSimpleObject() {
member1 = 11;
member2 = "hello";
member3 = "hello";
member4 = 3.14159265;
member5 = "hello world!";
}
另见:
// A test object that needs to be serialized.
[Serializable()]
public class TestSimpleObject {
public int member1;
public string member2;
public string member3;
public double member4;
// A field that is not serialized.
[NonSerialized()] public string member5;
public TestSimpleObject() {
member1 = 11;
member2 = "hello";
member3 = "hello";
member4 = 3.14159265;
member5 = "hello world!";
}
另见: