我在下面写class in to f#
using System.ComponentModel;
using System.Reflection;
namespace System
{
public static class EnumExtensions
{
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
public static string Description<TEnum>(this TEnum enumValue) where TEnum : struct
{
return GetEnumDescription((Enum)(object)(enumValue));
}
}
}
但是我被卡住了,有人能帮我吗
类似这样的代码应该可以达到这个效果:
let getEnumDescription value =
let fi =
value.GetType().GetField(value.ToString())
let attributes =
fi.GetCustomAttributes(typedefof<DescriptionAttribute>, false)
|> Array.map (fun x -> x :?> DescriptionAttribute)
if attributes.Length > 0 then
attributes.[0].Description
else
value.ToString()
那么你可以这样调用它:
let red = Color.Red |> getEnumDescription
let blue = Color.Blue |> getEnumDescription
printfn "Red is %snBlue is %s" red blue
//Red is Red
//Blue is Deep Blue