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

本文关键字:非常 相似 方法 许多 泛型 | 更新日期: 2023-09-27 18:37:04

我有很多类(超过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;
}

上面的代码表明这些方法只是get/set方法,它们比这更复杂一些,尽管为了简洁起见,我错过了这一点。这也是为什么这些方法不是匹配类的一部分(即类 CType1 中的 FetchType1F1

)的原因。

困扰我的是,除了处理的字段和列表之外,每个方法的内容几乎相同。我想我可以使用泛型来创建几个基本方法,但我随后在如何引用正确的字段方面苦苦挣扎:

public static String FetchGenericString <ListType> (List<ListType> aList, int aIndex) {
    //For now return empty string.
    return "";
}
public static Tuple<bool, String> FetchType1F1(int aIndex){
    String mResult=FetchGenericString(gListType1, 0);
}

我不确定如何将字段名称传递给 FetchGenericString,以便我可以调用它:

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);

但必须补充一点,变量名称的这些前缀并不能使阅读代码变得非常容易。您应该考虑删除它们。