Convert between IDictionary<string,object?> and C# object.
AOT friendly, Free of reflection.
using Tsinswreng.CsDictMapper;
namespace MyProjectNamespace; // don't put things in global namespace otherwise it may not work
public partial class Person{
public int Age{get;set;}
public string Name {get;set;}
}
[DictType(typeof(Person))]
//[DictType(typeof(MoreTypes))]
public partial class AppDictMapper{
public static AppDictMapper Inst{get;} = new();
}using Tsinswreng.CsDictMapper;
// object to dictionary:
var person = new Person{Age=22, Name="Tsinswreng"};
var dict = AppDictMapper.Inst.ToDictShallowT(person);
// the dict will be like {"Age":22, "Name":"Tsinswreng"}
// assign the dictionary to object:
var person2 = new Person();
AppDictMapper.Inst.AssignShallowT(person2, dict);
// the content of `person2` will be the same as `person`- Clone the repo
- In your .csproj file:
<ItemGroup>
<!-- reference the source generator assembly -->
<ProjectReference Include="../Tsinswreng.CsDictMapper/proj/Tsinswreng.CsDictMapper.SrcGen/Tsinswreng.CsDictMapper.SrcGen.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false"
/>
<!-- reference the API assembly, including Attributes, interfaces etc. -->
<ProjectReference Include="../Tsinswreng.CsDictMapper/proj/Tsinswreng.CsDictMapper/Tsinswreng.CsDictMapper.csproj" />
</ItemGroup>The class attached [DictType(typeof(T))] will automatically implement the interface IDictMapperShallow
namespace Tsinswreng.CsDictMapper;
using str = string;
public partial interface IDictMapperShallow{
public IDictionary<Type, IDictMapperForOneType> Type_Mapper{get;set;}
public IDictionary<str, object?> ToDictShallowT<T>(T Obj);
public IDictionary<str, object?> ToDictShallow(Type Type, object? Obj);
public IDictionary<str, Type> GetTypeDictShallowT<T>();
public IDictionary<str, Type> GetTypeDictShallow(Type Type);
public T AssignShallowT<T> (T Obj, IDictionary<str, object?> Dict);
public object AssignShallow(Type Type, object? Obj, IDictionary<str, object?> Dict);
}
public partial interface IDictMapperForOneType{
public Type TargetType{get;}
public IDictionary<str, object?> ToDictShallow(object Obj);
public IDictionary<str, Type> GetTypeDictShallow();
public object AssignShallow(object Obj, IDictionary<str, object?> Dict);
}