'How to serialize list or array using MetaLama in ToString TypeAspect
I am trying to write an TypeAspect using MetaLama framwerok that will serialize an object to it's string representation when it has a nested list type. Here is what I tried :
public class ToStringAttribute : TypeAspect
{
[Introduce(WhenExists = OverrideStrategy.Override, Name = "ToString")]
public string IntroducedToString()
{
var stringBuilder = new InterpolatedStringBuilder();
stringBuilder.AddText(meta.Target.Type.Name);
stringBuilder.AddText(" ");
var fields = meta.Target.Type.FieldsAndProperties.Where(f => !f.IsStatic)
.ToList();
var i = meta.CompileTime(0);
stringBuilder.AddText("{ ");
foreach (var field in fields)
{
if (i > 0)
{
stringBuilder.AddText(", ");
}
stringBuilder.AddText(field.Name);
stringBuilder.AddText(" : ");
if (field.Type.ToType() == typeof(string))
{
stringBuilder.AddText("'");
stringBuilder.AddExpression(field.Invokers.Final.GetValue(meta.This));
stringBuilder.AddText("'");
}
else if ((field.Type.ToType().IsArray || field.Type.ToType().IsCollectible) && !field.Type.ToType().IsPrimitive) // <- not filtering collection types
{
stringBuilder.AddText("[");
//foreach (var item in meta.Target.Type.FieldsAndProperties.Where(p => p.Type.ToType().IsCollectible)) <- I need the collection type properties
//{
//stringBuilder.AddExpression(item);
//stringBuilder.AddText(" : ");
//stringBuilder.AddExpression(item.Value);
//}
stringBuilder.AddText("]");
}
else
{
stringBuilder.AddExpression(field.Invokers.Final.GetValue(meta.This));
}
i++;
}
stringBuilder.AddText(" }");
return stringBuilder.ToValue();
}
}
}
Anyone can help? Am new with MetaLama, but I found it very interesting. thnx
Solution 1:[1]
This code will check if a type is enumerable:
var returnsEnumerable =
type is INamedType namedType
&& !type.Is( SpecialType.String )
&& namedType.AllImplementedInterfaces.Any( i => i.Name == "IEnumerable" );
You can try it online:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gael Fraiteur |