【发布时间】:2014-09-24 15:00:21
【问题描述】:
我正在尝试为名为@987654321@ 的第三方类创建代理项。我只需要序列化它的一些公共成员,包括对另一个此类实例的一些引用并公开Transforms 的内部列表。所以我为它写了代理,但我不确定是否可以在代理的字段上定义[ProtoMember] 属性,这是Transform 类型。还是应该是TransformSurrogate?现在我的代码是:
[ProtoContract(AsReferenceDefault = true)]
public class TransformSurrogate {
[ProtoMember(1)]
Vector3 localPosition { get; set; }
[ProtoMember(2)]
Vector3 localScale { get; set; }
[ProtoMember(3)]
Quaternion localRotation { get; set; }
[ProtoMember(4, AsReference = true)]
Transform parent { get; set; }
[ProtoMember(5, AsReference = true)]
List<Transform> children { get; set; }
public static explicit operator TransformSurrogate(Transform transform) {
if (transform == null) return null;
var surrogate = new TransformSurrogate();
surrogate.localPosition = transform.localPosition;
surrogate.localRotation = transform.localRotation;
surrogate.localScale = transform.localScale;
surrogate.parent = transform.parent;
surrogate.children = new List<Transform>();
for (int i = 0; i < transform.childCount; ++i) {
surrogate.children.Add(transform.GetChild(i));
}
return surrogate;
}
public static explicit operator Transform(TransformSurrogate surrogate) {
if (surrogate == null) return null;
var transform = new GameObject().transform;
transform.localPosition = surrogate.localPosition;
transform.localRotation = surrogate.localRotation;
transform.localScale = surrogate.localScale;
transform.parent = (Transform) surrogate.parent;
foreach (var child in surrogate.children) {
child.parent = transform;
}
return transform;
}
}
不要太在意Vector3 和Quaternion 类——它们很容易被序列化。所以我为Transform 定义了我自己的RuntimeTypeModel 类型,如下所示:
Model.Add(typeof(Transform), false).SetSurrogate(typeof(TransformSurrogate));
但是,我在反序列化过程中遇到错误,告诉我 Protobuf 无法在类之间进行转换。我认为这是因为在代理类中混合了原始类,但我不确定。
【问题讨论】:
-
这在依赖于非核心类型的复杂类型的上下文中很难回答;你有一个例子来说明只使用简单的本地类型的问题吗?
-
@MarcGravell 现在我正在尝试在更简单的环境中对这种情况进行建模,但是如果您想知道 Vector3 和 Quaternion 类型是什么 - 您可以跳过它们,因为它们是简单的结构并且我成功地序列化了它们.我现在主要关注的是 Transform 类。 Transform 是 Unity3D 内置类型,如果有帮助的话。
标签: c# serialization unity3d protocol-buffers protobuf-net