更新:
IParcelable 显然 cannot currently be implemented in Mono for Android .最后,我在类中使用了 .NET 序列化,然后将序列化数据打包/bundle 到 Android 特定代码中,效果很好。它还使类跨平台兼容,这是可取的。
原始问题:
我正在尝试将 Parcelable 实现为 Mono for Android 应用程序中类的一部分,但 Xamarin 的 Parcelable 文档是从 Android 文档中复制粘贴的:
http://androidapi.xamarin.com/?link=T%3aAndroid.OS.IParcelable
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
由于该文档是为 Java 编写的,因此对于 C# 来说基本上是错误的。我只是想知道是否有人知道如何将此代码转换为 C#。我在 CREATOR 字段上遇到了特别大的麻烦。
此外,由于我正在尝试编写以后可以移植到其他平台的代码,实现 Parcelable 的最佳方法是什么?我应该使用部分类使其成为类的一部分吗?
最佳答案
对于匿名内部类(对我来说是 AIC),我经常忘记的一件事是 AIC 中的“类型”不会直接转换为 C#——它们是接口(interface),这意味着 C# 的标准是以“I”开头。 '此外,每个 AIC 都必须在 c# 中显式实现。
以下有帮助吗?
public class Creator : IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
throw new NotImplementedException();
}
public Java.Lang.Object[] NewArray(int size)
{
throw new NotImplementedException();
}
public IntPtr Handle
{
get { throw new NotImplementedException(); }
}
}
然后:
public class MyParcelable : IParcelable
{
public int DescribeContents()
{
throw new NotImplementedException();
}
public void WriteToParcel(Parcel dest, int flags)
{
throw new NotImplementedException();
}
public IntPtr Handle
{
get { throw new NotImplementedException(); }
}
}
关于c# - 适用于 Android、Parcelable 和 C# 的 Mono - 文档有误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9074480/