C# 使用泛型简化许多非常相似的方法

C# 使用泛型简化许多非常相似的方法,c#,generics,C#,Generics,我有很多类(超过40个),每个类都有很多字段(通常是字符串或列表)。然后我有大约8-10个函数在每个类上工作(但是这些函数不是相关类的一部分…),除了它工作的字段名之外,每个函数几乎相同。因此: public static class CMix{ private static List<CType1> gListType1; private static List<CType2> gListType2; //... public st

我有很多类(超过40个),每个类都有很多字段(通常是字符串或列表)。然后我有大约8-10个函数在每个类上工作(但是这些函数不是相关类的一部分…),除了它工作的字段名之外,每个函数几乎相同。因此:

public static class CMix{

    private static List<CType1> gListType1;
    private static List<CType2> gListType2;

    //...

    public static Tuple<bool, String> FetchType1F1(int aIndex){
        //Bounds checking + return item from gListType1.
    }

    public static Tuple<boo, String> FetchType1F2(int aIndex){
        //Bounds checking + return item from gListType1.
    }

    //...

    public static Tuple<bool, ulong> FetchType2AB2(int aIndex){
        //Bounds checking + return item from gListType2.
    }

}

public class CType1{
    public String mF1;
    public String mF2;
    public ulong mF3;
}

public class CType2{
    public String mAB1;
    public ulong mAB2;
}
这甚至可能不是解决这个问题的最好办法,所以我会听取任何建议


谢谢。

您可以修改方法以包含要查找其属性的访问者:

  public static TValue FetchValue<TList, TValue>(List<TList> aList, int aIndex, Func<TList, TValue> valueSelector)
    {
        return valueSelector(aList[aIndex]);
    }
不过,必须补充的是,变量名的前缀并不能使读取代码变得非常容易。你应该考虑删除它们。

非常感谢。至于前缀,这是我多年前养成的习惯,而且似乎已经坚持了……;)
String mResult=FetchGenericString(gListType1, 0, mF1);
  public static TValue FetchValue<TList, TValue>(List<TList> aList, int aIndex, Func<TList, TValue> valueSelector)
    {
        return valueSelector(aList[aIndex]);
    }
String mResult=FetchGenericString(gListType1, 0, a => a.mF1);