代码之家  ›  专栏  ›  技术社区  ›  Jérôme MEVEL

在.NET标准中表示属性中的颜色

  •  3
  • Jérôme MEVEL  · 技术社区  · 8 年前

    例如:

    public class DesignAttribute : Attribute
    {
        public int Width { get; set; }
        public ??? BackgroundColor { get; set; }
    }
    

    问题是此属性应为常量或基元类型,并在编译时解决。

    System.Drawing.Color 也不是 int 对于ARGB表示,因为

    public class FooModel
    {
        [Required]
        public int Id { get; set; }
    
        [DesignAttribute(Width = 20, BackgroundColor = Color.Red.ToArgb())]
        public string Name { get; set; }
    }
    

    给我一个编译错误

    我也试着用 Byte[] string 并将其设置为 Color.Red.Name 不起作用。

    这个 System.Drawing.KnownColor Github thread )

    所以我想知道我在.NET标准中有哪些选择?如何将颜色表示为有效的属性参数?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Jérôme MEVEL    7 年前

    你不应该用GDI+ System.Drawing.Color 或WPF System.Windows.Media.Color

    public class DesignAttribute : Attribute
    {
        public int Width { get; set; }
        public string BackgroundColor { get; set; }
    }
    

    现在你可以:

    public class FooModel
    {
        [Required]
        public int Id { get; set; }
    
        [DesignAttribute(Width = 20, BackgroundColor = "red"]
        public string Name { get; set; }
    }
    

    当然,您必须支持多种格式(例如 #abcdef ),值可以按原样使用(例如,当呈现为HTML时)或转换为其他结构(例如,如果客户端是WPF或支持.NET标准的其他绘图框架)。在前一种情况下(假设您的目标是WPF应用程序中的.NET Framework),可以简单到:

    var color = (Color)colorConverter.ConvertFromString(attribute.BackgrouncColor);
    

    you found 你自己进去 .NET标准 这个 System.Drawing.Common Nuget软件包您有一个完美的匹配:

    var color = ColorTranslator.FromHtml(attribute.BackgroundColor);
    

    如果你想避免魔术字符串,那么你可以创建一个简单的颜色列表:

    static class Colors {
        public const string Red = "red";
    }
    

    这个列表甚至可以用一个简单的 T4 transformation (参见示例),可以使用以下命令获取列表:

    typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public)
        .Select(x => ((Color)x.GetValue(null)).ToString());
    

    [Serializable] .

        2
  •  1
  •   Scrobi    8 年前

    BackgroundColor 到一个常数。

    public class FooModel
    {
        [Required]
        public int Id { get; set; }
    
        [DesignAttribute(Width = 20, BackgroundColor = Constants.RedArgb)]
        public string Name { get; set; }
    }
    
    public static class Constants
    {
        public const int RedArgb = -65536;
    }