Using Read/Write AllFields

334 views
Skip to first unread message

nomauci

unread,
Jul 14, 2010, 10:58:29 AM7/14/10
to lidgren-network
When I try use WriteAllFields to fill NetOutgoingMessage, it did not
write field that in base class

class ClassA
{
int intA;
}

class ClassB : ClassA
{
int intB;
}
In this case, it just write intB only.

So I change coding of WriteAllFields and ReadAllFields like this.

public void WriteAllFields(object ob, BindingFlags flags)
{
if (ob == null)
return;
Type tp = ob.GetType();

FieldInfo[] fields = GetAllFields(tp, flags).ToArray();
NetIncomingMessage.SortMembersList(fields);

foreach (FieldInfo fi in fields)
{
object value = fi.GetValue(ob);

// find the appropriate Write method
MethodInfo writeMethod;
if (s_writeMethods.TryGetValue(fi.FieldType, out
writeMethod))
writeMethod.Invoke(this, new object[] { value });
else
throw new NetException("Failed to find write method
for type " + fi.FieldType);
}
}

private IEnumerable<FieldInfo> GetAllFields(Type t, BindingFlags
flags)
{
if (t == null)
return Enumerable.Empty<FieldInfo>();

return t.GetFields(flags).Union(GetAllFields(t.BaseType,
flags));
}

lidgren

unread,
Jul 14, 2010, 12:38:50 PM7/14/10
to lidgren-network
First; wrong forum. NetOutgoingMessage and WriteAllFields are part of
generation 3 of the library, it's preferred to post in the appropriate
forum:

http://groups.google.com/group/lidgren-network-gen3

However, Inherited members are not considered by the
WriteAllFields(object); but there is a WriteAllFields(object,
BindingFlags) which allows you to specify the binding flags you want
to use when retrieving the fields using reflection:

WriteAllFields(srcObject, BindingFlags.Public |
BindingFlags.Instance);
...
ReadAllFields(dstObject, BindingFlags.Public | BindingFlags.Instance);

... will serialize all public instance fields, including inherited
fields.

--michael
Reply all
Reply to author
Forward
0 new messages