简体   繁体   English

C# 将接受任何列表的方法<enum>并返回一个字符串数组</enum>

[英]C# A method that will accept any List<enum> and return a string array

There is an incredibly longer story to why I'm actually doing this, so I'm sure there is a better way as an overall approach.我为什么要这样做还有一个非常长的故事,所以我确信有一个更好的方法作为整体方法。 I don't have time to refactor the entire base structure and I want to minimize about 20k lines in the library to a method.我没有时间重构整个基本结构,我想将库中的大约 20k 行最小化为一个方法。 What I want to be able to do is take any List<Enum> and return a string[].我想要做的是获取任何List<Enum>并返回一个字符串 []。 My example is below, I'm sure I'm probably missing some sort of reflection.我的示例如下,我确定我可能缺少某种反思。 Thanks!谢谢!

public enum ActivityEnum
    {
        ID,
        ACTIVITYTYPEID,
        CAMPAIGNID,
        BUDGETID,
        LISTID
    }


public enum ActivityAttributeEnum
    {
        ID,
        ACTIVITYID,
        ACTIVITYATTRIBUTE,
        ENABLED,
        CREATEDBY,
        CREATEDDATE,
        LASTUPDATEBY,
        LASTUPDATEDATE
    }


public string[] myStrings(List<activtyEnum> activityEnums)
        {
            var array = new string[activityEnums.Count];
            for (int i = 0; i < activityEnums.Count; i++)
                array[i] = activityEnums[i].ToString();

            return array;

        }

What I'm unsure of is how to accept any enum.我不确定的是如何接受任何枚举。 In my example I have activityEnum, but I want the method to accept both ActivityAttribtueEnum and ActivityEnum.在我的示例中,我有 activityEnum,但我希望该方法同时接受 ActivityAttribtueEnum 和 ActivityEnum。 There are about 600 enums, so a generic way would be great.大约有 600 个枚举,所以一个通用的方法会很棒。

Thanks!谢谢!

private string[] GetNames<TEnum>(List<TEnum> enums) where TEnum : Enum
{
    return enums.Select(e => e.ToString()).ToArray();
}

You really ought to declare the parameter as type IEnumerable<TEnum> because that will work with a List<T> , an array, the result of a LINQ query and various other list types too.您确实应该将参数声明为IEnumerable<TEnum>类型,因为它也适用于List<T> 、数组、 LINQ 查询的结果以及各种其他列表类型。

Note that any list can have its items converted to a string array in this way too, so there's not really a need to to constrain the item type to be an enum .请注意,任何列表也可以通过这种方式将其项目转换为string数组,因此实际上不需要将项目类型限制为enum It won't actually hurt to define the method without a generic constraint.在没有通用约束的情况下定义方法实际上并没有什么坏处。 You might just want to change the name in that case, because the values returned might not be names.在这种情况下,您可能只想更改名称,因为返回的值可能不是名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM