类型“MyEnum”的表达式不能用于类型的参数 [英] Expression of type 'MyEnum' cannot be used for parameter of type

查看:205
本文介绍了类型“MyEnum”的表达式不能用于类型的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public enum MyEnum 
{

排队= 0,
[描述(进行中)]
In_progress = 2,
[描述(无回答)]
No_answer = 6,

}



public static class EnumToFrendlyString
{

public static string ToFrendlyString(此枚举值)
{
返回值.GetEnumDescription();
}


public static string GetEnumDescription(此枚举值)
{
FieldInfo fi = value.GetType()。GetField(value.ToString( ));

var attributes =
(DescriptionAttribute [])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);

if(attributes.Length> 0)
返回属性[0] .Description;

返回值.ToString();
}
}

当我尝试在Linq中使用此功能时,im获取错误

  var res = collection.AsQueryable()。其中​​(p => p.UserID == UserID).OrderByDescending (p => p.DateCreated).Select(p => new MyClass 
{
Date = p.DateCreated.ToString(),
Status = p.Status.ToFrendlyString() ,
})。Take(10).ToList();

如果我在同一个类中创建另一个函数,如

  private string MyStatusToString(MyEnum status)
{
return status.ToFrendlyString();
}

并更改我的Linq以使用此功能,然后一切正常。 >

错误

 DAL.MyEnum类型的表达式不能用于参数类型'System.Enum'的方法'System.String ToFrendlyString(System.Enum)'


解决方案

我不知道你可以使用枚举作为类似于这样的扩展方法的类型 - 尝试这样做。我已经自由地修复了代码,可以随便忽略这些变化:)

  public static class EnumToFrendlyString 
{
public static string ToFrendlyString< T>(此T值)
其中T:struct
{
return value.GetEnumDescription();
}

public static string GetEnumDescription< T>(此T值)
其中T:struct
{
返回EnumDescriptionCache< T&值];
}

私有静态类EnumDescriptionCache< T>
其中T:struct
{
public static Dictionary< T,string>描述=
Enum.GetValues(typeof(T))
.Cast< T>()
.ToDictionary(
value => value,
value => ; value.GetEnumDescriptionForCache());
}

私有静态字符串GetEnumDescriptionForCache< T>(此T值)
其中T:struct
{
if(!typeof(T) IsEnum)
{
throw new ArgumentException(仅用于枚举,value);


var descriptionAttribute = typeof(T)
.GetField(value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute),false)
.Cast< DescriptionAttribute>()
.FirstOrDefault();

return(descriptionAttribute!= null)
? descriptionAttribute.Description
:value.ToString();
}
}

我已经添加了一个私有的通用类来缓存您的枚举成员的描述,以避免大量运行时使用反射。它看起来有点奇怪的弹出和从类中的第一个缓存然后检索值,但它应该工作正常:)



我在这个答案仍然适用 - 传递给字典的枚举值没有验证,所以你可以通过调用((MyEnum)5367372)来崩溃它.ToFrendlyString()


I created Enum ToFrendlyString function for my enums, but i cant use in Linq.

 public enum MyEnum
    {

        Queued = 0,           
        [Description("In progress")]
        In_progress = 2,            
        [Description("No answer")]
        No_answer = 6,

    }



  public static class EnumToFrendlyString
    {

        public static string ToFrendlyString(this Enum value)
        {
            return value.GetEnumDescription();
        }


        public static string GetEnumDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            var attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false);

            if (attributes.Length > 0)
                return attributes[0].Description;

            return value.ToString();
        }
    }

When i try to use this function in Linq, im getting error

  var res = collection.AsQueryable().Where(p => p.UserID == UserID).OrderByDescending(p=> p.DateCreated).Select(p => new MyClass
                {                          
                     Date = p.DateCreated.ToString(),
                     Status = p.Status.ToFrendlyString(),                        
                }).Take(10).ToList();

If i make another function in same class, like

 private string MyStatusToString(MyEnum status)
       {
           return status.ToFrendlyString();
       }

and change my Linq to use this function, then everything works.

Error

Expression of type 'DAL.MyEnum' cannot be used for parameter of type 'System.Enum' of method 'System.String ToFrendlyString(System.Enum)'

解决方案

I'm not sure you can use Enum as the Type for an extension method like that - try this instead. I've taken the liberty of tidying the code up a bit, feel free to ignore those changes :)

public static class EnumToFrendlyString
{
    public static string ToFrendlyString<T>(this T value)
        where T : struct
    {
        return value.GetEnumDescription();
    }

    public static string GetEnumDescription<T>(this T value)
        where T : struct
    {
        return EnumDescriptionCache<T>.Descriptions[value];
    }

    private static class EnumDescriptionCache<T>
        where T : struct
    {
        public static Dictionary<T, string> Descriptions =
            Enum.GetValues(typeof(T))
                .Cast<T>()
                .ToDictionary(
                    value => value,
                    value => value.GetEnumDescriptionForCache());
    }

    private static string GetEnumDescriptionForCache<T>(this T value)
        where T : struct
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("Only use with enums", "value");
        }

        var descriptionAttribute = typeof(T)
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .Cast<DescriptionAttribute>()
            .FirstOrDefault();

        return (descriptionAttribute != null)
            ? descriptionAttribute.Description
            : value.ToString();
    }
}

I've added a private, generic class to cache the descriptions for your enum members to avoid lots of runtime use of reflection. It looks a bit odd popping in and out of the class to first cache then retrieve the values, but it should work fine :)

The warning I gave in this answer still applies - the enum value passed to the dictionary isn't validated, so you could crash it by calling ((MyEnum)5367372).ToFrendlyString().

这篇关于类型“MyEnum”的表达式不能用于类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆