基于属性/参数的通用列表/词典

时间:2018-07-19 15:58:12

标签: c# generics generic-programming

对于初学者,我已经基于使多个私有变量存储信息并在受影响的对象上获取/设置了该问题的变通方法。

此问题的范围仅供学习/参考。

场景: 我有一个管理多个对象的界面(此示例中为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

如果有人对如何实现此建议有任何建议或改进建议,请告诉我:)

1 个答案:

答案 0 :(得分:1)

对于存档,我可以使用上面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 { }