基于 Property/Parameter 的通用 List/Dictionary

Generic List/Dictionary based on Property/Parameter

对于初学者,我已经基于多个私有变量存储信息并在受影响的对象上 get/set 实现了这个问题的解决方法。

此问题的范围是 learning/reference。

场景: 我有一个管理多个对象的接口(本例中为 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;}

目标是能够引用 list/dictionary/array 类型可能发生变化的对象(类似于泛型)。这些类型不影响逻辑,它们被划分为单独的处理程序并在那里进行管理。

示例声明:

Dictionary<string,TypeA> myDictionary;
Dictionary<string,TypeB> myDictionary;

或作为列表:

class 富

List<TypeA> myValues
List<string> myKeys

class 酒吧

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 { }