【问题标题】:combining 2 methods into a generic method in c#在c#中将2个方法组合成一个泛型方法
【发布时间】:2022-06-10 20:05:06
【问题描述】:

我正在尝试找到一种方法将其变成一个通用方法,我可以将值解析为小数或整数。有谁知道这样做的好方法吗?

        private int ParseIntField(string value, int linecount, string fieldName)
        {
            if (!Int32.TryParse(value, out int result))
            {
                throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName} Value: {value}");
            }
            return result;
        }

        private decimal ParseDecimalField(string value, int linecount, string fieldName)
        {
            if (!decimal.TryParse(value, out decimal result))
            {
                throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName} Value: {value}");
            }
            return result;
        }

【问题讨论】:

  • 为什么?它正在工作,很清楚,很短 - 将它用于这两种类型只会让事情变得更加复杂。
  • 很难想象你可能需要这种方法的情况。
  • 我是学生,这不是出于实际原因,我被告知要看看我是否可以做到,老实说我很难过。
  • 如果不使用反射来尝试访问泛型类型上的TryParse 方法,则无法完成。不知道这意味着什么,我会回到你的导师那里叫他们出来。
  • 我同意,TryParse 无论如何只适用于少数类型,所以泛型的好处并不多

标签: c# generics


【解决方案1】:

没有真正好的方法可以为此使用通用方法,但您也许可以拆分方法以共享通用功能,例如:

int? ParseInt(string s) => int.TryParse(s, out r) ? r : null;
decimal? ParseDouble(string s) => decimal.TryParse(s, out r) ? r : null;
T ParseOrThrow<T>(string str, int linecount, string fieldName, Func<string, T?> parser){
    return parser(s) ?? throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName};
}

并像ParseOrThrow("5", 2, "five", ParseInt); 一样调用。但除非您有更多代码需要在不同类型之间共享,否则好处可能是微乎其微的。

【讨论】:

    【解决方案2】:

    这就是我最终的结果,到目前为止,它似乎运行良好。如果有任何问题,请告诉我!

    public static T TryParseAndException<T>(string value, int linecount, string fieldName)
            {
                T results;
                try
                {
                    results = (T)Convert.ChangeType(value, typeof(T));
                }
                catch (Exception)
                {
    
                    throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName} Value: {value}");
                }
                return results;
            }```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      相关资源
      最近更新 更多