Created
August 9, 2023 07:57
-
-
Save kamend/ddf30de73ae17017d3b85c0f984cc0a1 to your computer and use it in GitHub Desktop.
Holding unstructured data in a Dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
namespace DictExperiments | |
{ | |
public static class DictExt | |
{ | |
public class SceneObjectParser : IDisposable | |
{ | |
public Dictionary<string, PropertyValue> Dict { get; set; } | |
public string Name() | |
{ | |
return Dict["Name"].Str(); | |
} | |
public float Age() | |
{ | |
return Dict["Age"].Flt(); | |
} | |
public void Dispose() | |
{ | |
Dict = null; | |
} | |
} | |
private static SceneObjectParser _sceneObjectParser = new SceneObjectParser(); | |
public static string Str(this Dictionary<string, PropertyValue> dict,string Key) | |
{ | |
return dict[Key].Str(); | |
} | |
public static SceneObjectParser ToSceneObject(this Dictionary<string, object> dict) | |
{ | |
_sceneObjectParser.Dict = dict; | |
return _sceneObjectParser; | |
} | |
} | |
public interface IValue | |
{ | |
} | |
public struct StringValue : IValue | |
{ | |
public string Val; | |
public StringValue(string v) | |
{ | |
Val = v; | |
} | |
} | |
public struct FloatValue : IValue | |
{ | |
public float Val; | |
public FloatValue(float v) | |
{ | |
Val = v; | |
} | |
} | |
public struct PropertyValue | |
{ | |
public IValue Value; | |
public PropertyValue(IValue v) | |
{ | |
Value = v; | |
} | |
public PropertyValue(string str) | |
{ | |
Value = new StringValue(str); | |
} | |
public PropertyValue(float f) | |
{ | |
Value = new FloatValue(f); | |
} | |
public string Str() | |
{ | |
return ((StringValue)Value).Val; | |
} | |
public float Flt() | |
{ | |
return ((FloatValue)Value).Val; | |
} | |
public static PropertyValue Str(string value) | |
{ | |
return new PropertyValue(new StringValue(value)); | |
} | |
public static PropertyValue Flt(float value) | |
{ | |
return new PropertyValue(new FloatValue(value)); | |
} | |
} | |
public class DictionaryHelper : MonoBehaviour | |
{ | |
private Dictionary<string, PropertyValue> props = new Dictionary<string, PropertyValue>(); | |
// Start is called before the first frame update | |
void Start() | |
{ | |
props["Name"] = PropertyValue.Str("Kamen"); | |
props["Age"] = PropertyValue.Flt(12.0f); | |
using var obj = props.ToSceneObject(); | |
Debug.Log(obj.Name()); | |
Debug.Log(obj.Age()); | |
Debug.Log(props.Str("Name")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment