[英]C#: automatic conversion from enum to class
Consider this scenario. 考虑这种情况。
struct
Color
(written by someone else) 有一个struct
Color
(由其他人写) enum ColorCode
which implements html named color codes. enum ColorCode
实现了html命名的颜色代码。 ColorCode
to Color
有一个静态函数可以将ColorCode
转换为Color
I want to be able to do this: 我希望能够这样做:
Color tmp = ....; tmp = ColorCode.Aqua;
How do I do this without copy-pasting text 140 times? 如何在没有复制粘贴文本140次的情况下执行此操作?
I don't really care what ColorCode
is (enum, class, whatever) as long as the above line works. 只要上面的代码行,我就不在乎ColorCode
是什么(枚举,类,等等)。
Problem: 问题:
C# does not allow me to define operators for enums. C#不允许我为枚举定义运算符。 I also do not have any macros to make some nice human-readable table within ColorCode
. 我也没有任何宏来在ColorCode
制作一些漂亮的人类可读表格。
Restriction : 限制 :
Contents of ColorCode
should be available as int
s, but should be assignable/ convertible to Color
. ColorCode
内容应该以int
单位,但应该可以赋值/可转换为Color
。
Code fragments: 代码片段:
public enum ColorCode{
AliceBlue = 0xF0F8FF,
AntiqueWhite = 0xFAEBD7,
Aqua = 0x00FFFF,
Aquamarine = 0x7FFFD4,
Azure = 0xF0FFFF, ///Repeat 140 times
...
}
public static Color colorFromCode(ColorCode code){
....
}
You could write an extension method on the enum: 你可以在枚举上写一个扩展方法:
public static Color ToColor(this ColorCode colorCode)
{
...
}
Then you could have: 然后你可以:
Color tmp = ColorCode.Aqua.ToColor();
It's not quite an implicit conversion, but it's as readable as you're likely to get. 它不是一个隐含的转换,但它可以像你可能获得的那样可读。
You can make ColorCode
a struct (better than a class, because it really is just a value), and then define an implicit cast from ColorCode
to Color
: 你可以使ColorCode
成为一个结构(比一个类更好,因为它实际上只是一个值),然后定义从ColorCode
到Color
的隐式ColorCode
:
struct ColorCode
{
int hex;
public static readonly ColorCode
AliceBlue = 0xF0F8FF,
AntiqueWhite = 0xFAEBD7;
// and the rest of the ColorCodes
public static implicit operator Color(ColorCode cc)
{
return /* cc converted to a Color */;
}
public static implicit operator ColorCode(int cc)
{
return new ColorCode() { hex = cc };
}
}
The implicit cast from int
to Color
is just to make the definitions for your named color codes easier (so that you can do, for example, AliceBlue = 0xF0F8FF
). 从int
到Color
的隐式转换只是为了使命名颜色代码的定义更容易(例如,你可以这样做, AliceBlue = 0xF0F8FF
)。 At this point, you can easily and implicitly convert ColorCode
s to Color
s: 此时,您可以轻松地将ColorCode
转换为Color
s:
Color tmp = ColorCode.Aqua;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.