首页 > 解决方案 > 基于属性/参数的通用列表/字典

问题描述

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

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

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

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

示例声明:

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

或作为列表:

Foo 类

List<TypeA> myValues
List<string> myKeys

类酒吧

List<TypeB> myValues
List<string> myKeys

如果有人对如何实现这一点有任何建议,或者有改进的建议,请告诉我:)

标签: c#genericsgeneric-programming

解决方案


对于存档,我能够通过使用上面 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 { }

推荐阅读