当要参数化的类型的目标不是顶级属性时,如何创建泛型函数

本文关键字:何创建 创建 函数 泛型 类型 参数 目标 属性 | 更新日期: 2023-09-27 18:35:04

更一般地说,我想知道当要参数化的类型的目标不是顶级属性时,您如何制作泛型例程。

具体来说,我正在努力消除这两个函数的重复:

    private static string ExceptionMessage(Exception e)
    {
        string result = string.Empty;
        Exception exception = e;
        while (exception != null)
        {
            if (e.Message != null)
            {
                if (result.Length > 0)
                {
                    result += Separator;
                }
                result += exception.Message;
            }
            exception = exception.InnerException;
        }
        return result;
    }
    private static string Tag(Exception e)
    {
        string result = string.Empty;
        Exception exception = e;
        while (exception != null)
        {
            if (e.TargetSite != null)
            {
                if (result.Length > 0)
                {
                    result += Separator;
                }
                result += exception.TargetSite.Name;
            }
            exception = exception.InnerException;
        }
        return result;
    }

当要参数化的类型的目标不是顶级属性时,如何创建泛型函数

(目前(没有办法通过泛型显式地做到这一点,我认为向你的函数发送布尔参数不是你要找的。

您可以通过传入一个闭包来解决此问题,该闭包提取所需的 Exception 实例部分,如下例所示:

private static string AggregateException(Exception e, Func<Exception,string> getPart){
        string result = string.Empty;
        Exception exception = e;
        while (exception != null)
        {
            if (e.Message != null)
            {
                if (result.Length > 0)
                {
                    result += Separator;
                }
                result += getPart(exception);
            }
            exception = exception.InnerException;
        }
        return result;
}

示例用法:

    string msg = AggregateException(myEx, (ex) => ex.Message);
    string tag = AggregateException(myEx, (ex) => ex.TargetSite.Name);