Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从值类型获取小写字符串而不首先转换为字符串_C# - Fatal编程技术网

C# 从值类型获取小写字符串而不首先转换为字符串

C# 从值类型获取小写字符串而不首先转换为字符串,c#,C#,我有一个枚举。我需要获取此枚举的小写字符串表示形式。有没有一种方法可以在不必先创建两个字符串的情况下获取小写字母,即enum.ToString.ToLower。是否有一些FormatProvider可以传递到ToString中,只创建一个小写字符串,就是这样如果没有某种ToString方法,我认为没有一种方法可以从非字符串值使用string的ToLower方法。 如果是语法问题,可以将其作为扩展方法: public static string ToLowerString(this YourEnu

我有一个枚举。我需要获取此枚举的小写字符串表示形式。有没有一种方法可以在不必先创建两个字符串的情况下获取小写字母,即enum.ToString.ToLower。是否有一些FormatProvider可以传递到ToString中,只创建一个小写字符串,就是这样

如果没有某种ToString方法,我认为没有一种方法可以从非字符串值使用string的ToLower方法。 如果是语法问题,可以将其作为扩展方法:

public static string ToLowerString(this YourEnum enumValue) => enumValue.ToString().ToLower();
把它叫做:

YourEnum.SomeEnumValue.ToLowerString();
编辑


由于OP说他/她试图避免开销,我猜Theodor Dictionary建议的字典方法是一个更好的解决方案。

您可以构建一个查找字典,在启动时或第一次需要时初始化一次,并使用它来获得小写值:

public static Dictionary<TEnum, string> BuildEnumToStringMapping<TEnum>()
    where TEnum: struct
{
        if (!typeof(TEnum).IsEnum)
        {
            throw new ArgumentException("TEnum is not an enum.");
        }

        return Enum.GetValues(typeof(TEnum))
            .OfType<TEnum>()
            .ToDictionary(e => e, e => e.ToString().ToLower());
}
用法:

var lookup = BuildEnumToStringMapping<MyEnum>();
Console.WriteLine(lookup[MyEnum.Value]);

实现这一点的方法不多,因为您不需要两个字符串,这将使使用ToString.ToLower的可能性无效

我建议使用命名空间System.ComponentModel中的DescriptionAttribute

向枚举的每个成员添加DescriptionAttribute

public enum Items
{
    [Description("item1")]
    Item1 = 1,

    [Description("item2")]
    Item2 = 2,
}
然后在需要时使用反射来获得友好的小写名称

public static string GetDescription(Enum en)
{
    Type type = en.GetType();

    MemberInfo[] memInfo = type.GetMember(en.ToString());

    if (memInfo != null && memInfo.Length > 0)
    {
        object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            return ((DescriptionAttribute)attrs[0]).Description;
        }
    }

    return en.ToString();
}

参考:查看更多详细信息。

键入.ToString.ToLower太费事了?使用一个用小写字符串表示的字典怎么样?为每个枚举项使用属性[Descriptionlowercase]怎么样?额外的字符串可能对性能影响很小。但是你不应该太担心这一点,如果你有表现问题,你无论如何都应该衡量。@JohanP这里有一篇讨论这个话题的好帖子:我没有投反对票,但这可能是你的问题被否决的部分原因。如果你想/需要进行微优化,你可能应该证明你的担忧确实是一个瓶颈。只有当数字表明微优化很重要时,它才是重要的。你的问题可以解释为,我想去掉多余的字符串,因为有些人不喜欢它,这可能是理所当然的。它基本上做了同样的事情,可能加上扩展方法的开销。OP提到他/她关心的是创建两个字符串,而不是每次都必须键入.ToString.ToLower。@AhmedAbdelhameed是的,我是在讨论语法问题。我没注意到那句话。附加信息应作为编辑添加到问题中,而不是添加到评论中。@kame否。不会添加。它将返回Item1,而不是lowecase Item1。