[英]C# - Extensible method for adding variable types to a dictionary management class
我目前正在研究一種用於從主詞典類存儲和檢索數據的系統。 想象這樣的事情:
public class Manager {
Dictionary<string, Category> _categories;
public T GetValue<T>(string category, string id){
return _categories[category].GetValue<T>(id);
}
}
public class Category {
Dictionary<string, Category> _subCategories;
// How could I approach something like this?
Dictionary<T, Dictionary<string, IElementExample<T>> _categoryDict;
public T GetValue<T>(string id){
if (_categoryDict.ContainsKey(T)){
return _categoryDict[T][id];
}
return default(T);
}
public SetValue<T>(string id, T value){
if (_categoryDict.ContainsKey(T)){
if (_categoryDict[T].ContainsKey(id)){
_categoryDict[T][id] = value;
} else {
_categoryDict[T].Add(id, value);
}
} else {
_categoryDict.Add(T, new Dictionary<string, IElementExample<T>>());
_categoryDict[T].Add(id, value);
}
}
}
//
public interface IElementExample<T> {
T Value {get;set;}
string Id {get;set;}
string Comment{get;set;}
string Serialize();
void Deserialize(string serial);
}
public class StringElement : IElementExample<string> {
string m_value;
string m_id;
string m_comment;
string Value { get { return m_value; }}
string Id { get { return m_id; }}
string Comment { get { return m_comment; }}
string Serialize(){
}
void Deserialize(){
}
}
讓我絆倒的是,顯然我實際上不能擁有Dictionary<T, Dictionary<string, IElementExample<T>>
。 有人對我如何能夠完成這樣的事情有任何想法嗎?
這里的目標是創建一個可以存儲大量數據(用於游戲配置變量)的主位置,然后我將在該位置對XML進行序列化/反序列化。 我已經有一些東西可以解決這個問題,並且效果很好,但是如果不編輯Manager / Category類來添加支持,就不可能添加對新數據類型的支持(目前,它不是GetValue,而是GetString / GetFloat / GetInt / GetBool / GetVector3 ...等)。
通過添加“ where”類型約束以確保它實現了我的接口,我可以確保它實際上只能用於設計用於它的類。 我只是不確定如何設置我的“類別”類,以使其可以存儲和檢索任何“ IExampleInterface <>”-如果可能的話。
我希望能夠將其用於不同的項目,這些項目都包含主要類型(字符串/整數/浮點數/布爾...)-但也具有自己的自定義結構和類。
預先感謝您提供任何有關此問題的意見,我一直在嘗試自己解決問題-但是,這肯定會使我受益匪淺。
我沒有完成所有代碼,但看起來您想要一個
Dictionary<object, Dictionary<string, object> _categoryDict;
或一個
Dictionary<Type, Dictionary<string, object> _categoryDict;
您正確地發現泛型不是“動態的”。 如果要混合使用不同的類型,則需要進行類型轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.