Unity/Unity 리서치
Dictionary와 Object 변환
lipnus
2021. 7. 10. 15:08
반응형
Firebase는 Dictionary이고, 관리의 편의를 위해 객체로 변환하고자 할 때,
상호 변환이 가능한 코드.
static으로 선언해서 사용하고, 제네릭으로 구현되어 있음.
Code
using System.Collections.Generic;
using System.Reflection;
public static class ObjectExtensions
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
var someObject = new T();
var someObjectType = someObject.GetType();
foreach (var item in source)
{
someObjectType
.GetProperty(item.Key)
.SetValue(someObject, item.Value, null);
}
return someObject;
}
public static IDictionary<string, object> AsDictionary(
this object source,
BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null)
);
}
}
[Unity][c#] Firebase 에서 받은 데이터를 객체로 변환하기
유니티에서 파이어베이스의 값을 가져와 dictionary형태로 받았는데, 바로 내가 원하는 오브젝트 형식으로 변환해서 관리하고싶을때 이 방법을 사용하면 된다. 스태틱 클래스 생성 1 2 3 4 5 6 7 8 9 10
chopchops.tistory.com
반응형