A property set for Unity that serializes to string
$begingroup$
This a Dictionary<string,string>
I can attach to GameObject
and that is serializable since Unity cannot serialize them by default.
I decided to leverage TypeDescriptor
to be able to convert any type of convertible object instead of adding numerous overloads such as GetInt
, GetFloat
, GetBool
, GetString
.
Small drawback: it is inherently slower since TypeDescriptor
uses reflection.
I decided to not implement IDictionary<TKey,TValue>
for a couple of reasons:
- exposing
Keys
property would be confusing since values are not allstring
- the enumerator makes little sense as well unless it returns
object
values - there are many members that I will never use from it
It works as expected, simple and straightforward but improvements are welcome!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;
namespace ZeroAG.Scene
{
[SuppressMessage("ReSharper", "IdentifierTypo")]
public class PropertySet : MonoBehaviour, IPropertySet, ISerializationCallbackReceiver
{
internal const string DictionaryKeysProperty = nameof(_dictionaryKeys);
internal const string DictionaryValsProperty = nameof(_dictionaryVals);
private Dictionary<string, string> _dictionary = new Dictionary<string, string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryKeys = new List<string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryVals = new List<string>();
#region IPropertySet Members
public void Clear()
{
_dictionary.Clear();
}
public bool ContainsKey(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.ContainsKey(key);
}
public T GetValue<T>(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertFrom(typeof(string)))
throw new InvalidCastException($"Cannot convert from {typeof(string)} to {typeof(T)}.");
var value = _dictionary[key];
var o = converter.ConvertFromInvariantString(value);
if (o is T result)
return result;
throw new InvalidCastException($"Converted value is not of type {typeof(T)}.");
}
public bool Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.Remove(key);
}
public void SetValue<T>(string key, T value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertTo(typeof(string)))
throw new InvalidOperationException($"Cannot convert from {typeof(T)} to {typeof(string)}.");
var result = converter.ConvertToInvariantString(value);
AddOrUpdate(key, result);
}
public bool TryGetValue<T>(string key, out T result)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
try
{
result = GetValue<T>(key);
return true;
}
catch
{
result = default(T);
return false;
}
}
#endregion
#region ISerializationCallbackReceiver Members
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
_dictionary = _dictionaryKeys.Zip(_dictionaryVals, (k, v) => new {k, v}).ToDictionary(s => s.k, s => s.v);
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
_dictionaryKeys = _dictionary.Keys.ToList();
_dictionaryVals = _dictionary.Values.ToList();
}
#endregion
private void AddOrUpdate([NotNull] string key, string value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (_dictionary.ContainsKey(key))
{
_dictionary[key] = value;
}
else
{
_dictionary.Add(key, value);
}
}
}
}
c# dictionary unity3d type-safety
$endgroup$
add a comment |
$begingroup$
This a Dictionary<string,string>
I can attach to GameObject
and that is serializable since Unity cannot serialize them by default.
I decided to leverage TypeDescriptor
to be able to convert any type of convertible object instead of adding numerous overloads such as GetInt
, GetFloat
, GetBool
, GetString
.
Small drawback: it is inherently slower since TypeDescriptor
uses reflection.
I decided to not implement IDictionary<TKey,TValue>
for a couple of reasons:
- exposing
Keys
property would be confusing since values are not allstring
- the enumerator makes little sense as well unless it returns
object
values - there are many members that I will never use from it
It works as expected, simple and straightforward but improvements are welcome!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;
namespace ZeroAG.Scene
{
[SuppressMessage("ReSharper", "IdentifierTypo")]
public class PropertySet : MonoBehaviour, IPropertySet, ISerializationCallbackReceiver
{
internal const string DictionaryKeysProperty = nameof(_dictionaryKeys);
internal const string DictionaryValsProperty = nameof(_dictionaryVals);
private Dictionary<string, string> _dictionary = new Dictionary<string, string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryKeys = new List<string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryVals = new List<string>();
#region IPropertySet Members
public void Clear()
{
_dictionary.Clear();
}
public bool ContainsKey(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.ContainsKey(key);
}
public T GetValue<T>(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertFrom(typeof(string)))
throw new InvalidCastException($"Cannot convert from {typeof(string)} to {typeof(T)}.");
var value = _dictionary[key];
var o = converter.ConvertFromInvariantString(value);
if (o is T result)
return result;
throw new InvalidCastException($"Converted value is not of type {typeof(T)}.");
}
public bool Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.Remove(key);
}
public void SetValue<T>(string key, T value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertTo(typeof(string)))
throw new InvalidOperationException($"Cannot convert from {typeof(T)} to {typeof(string)}.");
var result = converter.ConvertToInvariantString(value);
AddOrUpdate(key, result);
}
public bool TryGetValue<T>(string key, out T result)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
try
{
result = GetValue<T>(key);
return true;
}
catch
{
result = default(T);
return false;
}
}
#endregion
#region ISerializationCallbackReceiver Members
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
_dictionary = _dictionaryKeys.Zip(_dictionaryVals, (k, v) => new {k, v}).ToDictionary(s => s.k, s => s.v);
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
_dictionaryKeys = _dictionary.Keys.ToList();
_dictionaryVals = _dictionary.Values.ToList();
}
#endregion
private void AddOrUpdate([NotNull] string key, string value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (_dictionary.ContainsKey(key))
{
_dictionary[key] = value;
}
else
{
_dictionary.Add(key, value);
}
}
}
}
c# dictionary unity3d type-safety
$endgroup$
add a comment |
$begingroup$
This a Dictionary<string,string>
I can attach to GameObject
and that is serializable since Unity cannot serialize them by default.
I decided to leverage TypeDescriptor
to be able to convert any type of convertible object instead of adding numerous overloads such as GetInt
, GetFloat
, GetBool
, GetString
.
Small drawback: it is inherently slower since TypeDescriptor
uses reflection.
I decided to not implement IDictionary<TKey,TValue>
for a couple of reasons:
- exposing
Keys
property would be confusing since values are not allstring
- the enumerator makes little sense as well unless it returns
object
values - there are many members that I will never use from it
It works as expected, simple and straightforward but improvements are welcome!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;
namespace ZeroAG.Scene
{
[SuppressMessage("ReSharper", "IdentifierTypo")]
public class PropertySet : MonoBehaviour, IPropertySet, ISerializationCallbackReceiver
{
internal const string DictionaryKeysProperty = nameof(_dictionaryKeys);
internal const string DictionaryValsProperty = nameof(_dictionaryVals);
private Dictionary<string, string> _dictionary = new Dictionary<string, string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryKeys = new List<string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryVals = new List<string>();
#region IPropertySet Members
public void Clear()
{
_dictionary.Clear();
}
public bool ContainsKey(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.ContainsKey(key);
}
public T GetValue<T>(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertFrom(typeof(string)))
throw new InvalidCastException($"Cannot convert from {typeof(string)} to {typeof(T)}.");
var value = _dictionary[key];
var o = converter.ConvertFromInvariantString(value);
if (o is T result)
return result;
throw new InvalidCastException($"Converted value is not of type {typeof(T)}.");
}
public bool Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.Remove(key);
}
public void SetValue<T>(string key, T value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertTo(typeof(string)))
throw new InvalidOperationException($"Cannot convert from {typeof(T)} to {typeof(string)}.");
var result = converter.ConvertToInvariantString(value);
AddOrUpdate(key, result);
}
public bool TryGetValue<T>(string key, out T result)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
try
{
result = GetValue<T>(key);
return true;
}
catch
{
result = default(T);
return false;
}
}
#endregion
#region ISerializationCallbackReceiver Members
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
_dictionary = _dictionaryKeys.Zip(_dictionaryVals, (k, v) => new {k, v}).ToDictionary(s => s.k, s => s.v);
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
_dictionaryKeys = _dictionary.Keys.ToList();
_dictionaryVals = _dictionary.Values.ToList();
}
#endregion
private void AddOrUpdate([NotNull] string key, string value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (_dictionary.ContainsKey(key))
{
_dictionary[key] = value;
}
else
{
_dictionary.Add(key, value);
}
}
}
}
c# dictionary unity3d type-safety
$endgroup$
This a Dictionary<string,string>
I can attach to GameObject
and that is serializable since Unity cannot serialize them by default.
I decided to leverage TypeDescriptor
to be able to convert any type of convertible object instead of adding numerous overloads such as GetInt
, GetFloat
, GetBool
, GetString
.
Small drawback: it is inherently slower since TypeDescriptor
uses reflection.
I decided to not implement IDictionary<TKey,TValue>
for a couple of reasons:
- exposing
Keys
property would be confusing since values are not allstring
- the enumerator makes little sense as well unless it returns
object
values - there are many members that I will never use from it
It works as expected, simple and straightforward but improvements are welcome!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;
namespace ZeroAG.Scene
{
[SuppressMessage("ReSharper", "IdentifierTypo")]
public class PropertySet : MonoBehaviour, IPropertySet, ISerializationCallbackReceiver
{
internal const string DictionaryKeysProperty = nameof(_dictionaryKeys);
internal const string DictionaryValsProperty = nameof(_dictionaryVals);
private Dictionary<string, string> _dictionary = new Dictionary<string, string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryKeys = new List<string>();
[SerializeField]
[HideInInspector]
private List<string> _dictionaryVals = new List<string>();
#region IPropertySet Members
public void Clear()
{
_dictionary.Clear();
}
public bool ContainsKey(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.ContainsKey(key);
}
public T GetValue<T>(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertFrom(typeof(string)))
throw new InvalidCastException($"Cannot convert from {typeof(string)} to {typeof(T)}.");
var value = _dictionary[key];
var o = converter.ConvertFromInvariantString(value);
if (o is T result)
return result;
throw new InvalidCastException($"Converted value is not of type {typeof(T)}.");
}
public bool Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _dictionary.Remove(key);
}
public void SetValue<T>(string key, T value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
var converter = TypeDescriptor.GetConverter(typeof(T));
if (!converter.CanConvertTo(typeof(string)))
throw new InvalidOperationException($"Cannot convert from {typeof(T)} to {typeof(string)}.");
var result = converter.ConvertToInvariantString(value);
AddOrUpdate(key, result);
}
public bool TryGetValue<T>(string key, out T result)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
try
{
result = GetValue<T>(key);
return true;
}
catch
{
result = default(T);
return false;
}
}
#endregion
#region ISerializationCallbackReceiver Members
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
_dictionary = _dictionaryKeys.Zip(_dictionaryVals, (k, v) => new {k, v}).ToDictionary(s => s.k, s => s.v);
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
_dictionaryKeys = _dictionary.Keys.ToList();
_dictionaryVals = _dictionary.Values.ToList();
}
#endregion
private void AddOrUpdate([NotNull] string key, string value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (_dictionary.ContainsKey(key))
{
_dictionary[key] = value;
}
else
{
_dictionary.Add(key, value);
}
}
}
}
c# dictionary unity3d type-safety
c# dictionary unity3d type-safety
asked 7 mins ago
AybeAybe
3921314
3921314
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213432%2fa-property-set-for-unity-that-serializes-to-string%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213432%2fa-property-set-for-unity-that-serializes-to-string%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown