【问题标题】:Use a delegate to merge two functions together使用委托将两个函数合并在一起
【发布时间】:2021-03-17 14:29:35
【问题描述】:

我有以下两个功能:

public static Dictionary<int, string> GetEnumLocalizations<T>()
    where T : struct
{
    return Enum.GetValues(typeof(T))
        .Cast<object>()
        .ToDictionary(enumValue => (int)enumValue, enumObject => ((Enum)enumObject).ToLocalizedValue());
}

public static Dictionary<int, string> GetEnumDescriptions<T>()
    where T : struct
{
    return Enum.GetValues(typeof(T))
        .Cast<object>()
        .ToDictionary(enumValue => (int)enumValue, enumObject => ((Enum)enumObject).GetDescription());
}

public static string GetDescription(this Enum value)
{
    return ...
}

public static string ToLocalizedValue(this Enum value)
{
    return ...
}

如果我没记错的话,应该可以将GetEnumLocalizations()GetEnumDescriptions()合并为一个函数,并使用委托参数来解析((Enum)enumObject).ToLocalizedValue())((Enum)enumObject).GetDescription())部分。

这可能吗?我在尝试这样做时被卡住了。在伪代码中,我在想类似的东西:

public static Dictionary<int, string> GetEnumValues<T>(delegate someFunction)
    where T : struct
{
    return Enum.GetValues(typeof(T))
        .Cast<object>()
        .ToDictionary(enumValue => (int)enumValue, someFunction);
}

【问题讨论】:

    标签: c# delegates


    【解决方案1】:

    当然,就用这个:

    public static Dictionary<int, string> GetEnumValues<T>(Func<Enum, string> someFunction)
        where T : struct
    {
        return Enum.GetValues(typeof(T))
            .Cast<object>()
            .ToDictionary(enumValue => (int)enumValue, enumObject => someFunction((Enum)enumObject);
    }
    

    现在你应该可以这样称呼它了:

    GetEnumValues<MyEnum>(x => x.ToLocalizedValue());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      相关资源
      最近更新 更多