c# - 基于属性/参数的通用列表/字典
问题描述
对于初学者,我已经基于多个私有变量存储信息并在受影响的对象上获取/设置,实现了针对此问题的解决方法。
此问题的范围是供学习/参考。
场景:我有一个管理多个对象的接口(本例中为 2 个)。
interface Imoon
??? SomePropertyName {get;set;}
class Foo : Imoon
public TypeA SomePropertyName {get;set;}
public enumMyType TypeStorage {get;set}
class Bar : Imoon
public TypeB SomePropertyName {get;set;}
public enumMyType TypeStorage {get;set;}
目标是能够引用类型可能发生变化的对象列表/字典/数组(类似于泛型)。这些类型不会影响逻辑,它们被划分为单独的处理程序并在那里进行管理。
一旦声明,对象的类型就不会改变。
Enumerable 中的所有元素的类型都相同,但是在不同对象之间可能会发生变化。
示例声明:
Dictionary<string,TypeA> myDictionary;
Dictionary<string,TypeB> myDictionary;
或作为列表:
Foo 类
List<TypeA> myValues
List<string> myKeys
类酒吧
List<TypeB> myValues
List<string> myKeys
如果有人对如何实现这一点有任何建议,或者有改进的建议,请告诉我:)
解决方案
对于存档,我能够通过使用上面 johnny5 推荐的通用接口来达到预期的结果。我已经包含了一个解决方案的示例,以及如何使用给定的类型 (TypeA) 来实现它,它也可以在 TypeB 上完成。
public interface ICollection<T>
{
Dictionary<string,T> TypeDictionary { get; set; }
void AddToDictionary(Dictionary<string,T> Addition
int FileCount { get; }
}
public class TypeACollection : ICollection<TypeA>
{
private Dictionary<string,TypeA> myTypeDictionary = new Dictionary<string, TypeA>();
public void AddToDictionary(Dictionary<string, TypeA> Addition)
{
foreach (var keyValuePair in Addition)
{
TypeDictionary[keyValuePair.Key] = keyValuePair.Value;
}
}
public Dictionary<string, TypeA> GetTypeDictionary()
{
return TypeDictionary;
}
private void ClearDictionary()
{
TypeDictionary.Clear();
}
public Dictionary<string, TypeA> TypeDictionary {
get { return myTypeDictionary; }
set { myTypeDictionary = value; }
}
public int FileCount {get { return TypeDictionary.Keys.Count; }}
}
public class TypeA { }
public class TypeB { }
推荐阅读
- c# - 将子模型传递到视图渲染的 LINQ 查询在视图中创建重复元素
- amazon-web-services - AWS Lambda CI/CD 流程
- javascript - 如何通过html创建一个可以下载/打印为pdf格式的文档页面
- python - (python) 让一个字符串被识别为一个已经定义的变量
- javascript - 使用 javascript 仅更改类元素数组中第一个元素的样式
- vue.js - vue中的多个vuex存储
- jquery - 如何从引导模式弹出窗口打开外部 url,如 https://login.microsoft.com
- python - InvalidArgumentError:设备规范格式错误
- python - 通过反向传播对贝叶斯使用局部重新参数化技巧时正确的损失函数
- r-markdown - 将 R markdown (Rmd) 中的非 ascii 字符渲染为 HTML 和 PDF