MessagePackFormatterAttribute supports object[] arguments

This commit is contained in:
neuecc 2017-06-29 16:03:51 +09:00
Родитель 6a592a35f5
Коммит d857f75622
3 изменённых файлов: 59 добавлений и 1 удалений

Просмотреть файл

@ -58,10 +58,17 @@ namespace MessagePack
public class MessagePackFormatterAttribute : Attribute
{
public Type FormatterType { get; private set; }
public object[] Arguments { get; private set; }
public MessagePackFormatterAttribute(Type formatterType)
{
this.FormatterType = formatterType;
}
public MessagePackFormatterAttribute(Type formatterType, params object[] arguments)
{
this.FormatterType = formatterType;
this.Arguments = arguments;
}
}
}

Просмотреть файл

@ -33,8 +33,15 @@ namespace MessagePack.Resolvers
return;
}
if (attr.Arguments == null)
{
formatter = (IMessagePackFormatter<T>)Activator.CreateInstance(attr.FormatterType);
}
else
{
formatter = (IMessagePackFormatter<T>)Activator.CreateInstance(attr.FormatterType, attr.Arguments);
}
}
}
}
}

Просмотреть файл

@ -134,6 +134,44 @@ namespace MessagePack.Tests
public int A { get; set; }
}
[MessagePackFormatter(typeof(NoObjectFormatter), CustomyEnumObject.C)]
class CustomClassObjectWithArgument
{
int X;
public CustomClassObjectWithArgument(int x)
{
this.X = x;
}
public int GetX()
{
return X;
}
class NoObjectFormatter : IMessagePackFormatter<CustomClassObjectWithArgument>
{
CustomyEnumObject x;
public NoObjectFormatter(CustomyEnumObject x)
{
this.x = x;
}
public CustomClassObjectWithArgument Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
{
var r = MessagePackBinary.ReadInt32(bytes, offset, out readSize);
return new CustomClassObjectWithArgument(r);
}
public int Serialize(ref byte[] bytes, int offset, CustomClassObjectWithArgument value, IFormatterResolver formatterResolver)
{
return MessagePackBinary.WriteInt32(ref bytes, offset, value.X * (int)x);
}
}
}
T Convert<T>(T value)
{
return MessagePackSerializer.Deserialize<T>(MessagePackSerializer.Serialize(value, MessagePack.Resolvers.StandardResolver.Instance), MessagePack.Resolvers.StandardResolver.Instance);
@ -148,5 +186,11 @@ namespace MessagePack.Tests
Convert((CustomyEnumObject)(1234)).Is(CustomyEnumObject.B);
Convert<ICustomInterfaceObject>(new HogeMoge { A = 999 }).A.Is(999);
}
[Fact]
public void WithArg()
{
Convert(new CustomClassObjectWithArgument(999)).GetX().Is(999 * 2);
}
}
}