如何将ConsoleColor
转换为Color
类型?
我需要这个来创建这个方法的重载,它应该返回一个颜色而不是Consolecolor:
''' <summary>
''' Generates a random ConsoleColor color.
''' </summary>
''' <returns>ConsoleColor.</returns>
Public Shared Function [ConsoleColor]() As ConsoleColor
Dim Rand As New Random
Return [Enum].Parse(GetType(ConsoleColor),
Rand.Next(0, 15))
End Function
这是我尝试过的,但有时返回的颜色为空,因为ConsoleColor名称未知:
''' <summary>
''' Generates a random QB color.
''' </summary>
''' <returns>Color.</returns>
Public Shared Function QB() As Color
Dim Rand As New Random
Return Color.FromName([Enum].Parse(GetType(ConsoleColor),
Rand.Next(0, 15)).ToString)
End Function
PS:我想避免使用旧的VB6方法(QBColor函数)。
答案 0 :(得分:8)
我今天自己有这个问题,并且不能同意目前的答案。
我最终检查了所有值,发现这些值非常不同,我不知道为什么人们会建议按名称转换&#39;。
## Name Actual Drawing.Color of same name
0 Black #000000 #000000
1 DarkBlue #000080 #00008B
2 DarkGreen #008000 #006400
3 DarkCyan #008080 #008B8B
4 DarkRed #800000 #8B0000
5 DarkMagenta #800080 #8B008B
6 DarkYellow #808000 #000000
7 Gray #C0C0C0 #808080
8 DarkGray #808080 #A9A9A9
9 Blue #0000FF #0000FF
10 Green #00FF00 #008000
11 Cyan #00FFFF #00FFFF
12 Red #FF0000 #FF0000
13 Magenta #FF00FF #FF00FF
14 Yellow #FFFF00 #FFFF00
15 White #FFFFFF #FFFFFF
答案 1 :(得分:2)
怎么样,
Module ColorExtension
<Extension()>
Public Function DrawingColor(ByVal color As ConsoleColor) As Color
Select color
Case ConsoleColor.Black
Return Color.Black
Case ConsoleColor.Blue
Return Color.Blue
Case ConsoleColor.Cyan
Return Color.Cyan
Case ConsoleColor.DarkBlue
Return ColorTranslator.FromHtml("#000080")
Case ConsoleColor.DarkGray
Return ColorTranslator.FromHtml("#808080")
Case ConsoleColor.DarkGreen
Return ColorTranslator.FromHtml("#008000")
Case ConsoleColor.DarkMagenta
Return ColorTranslator.FromHtml("#800080")
Case ConsoleColor.DarkRed
Return ColorTranslator.FromHtml("#800000")
Case ConsoleColor.DarkYellow
Return ColorTranslator.FromHtml("#808000")
Case ConsoleColor.Gray
Return ColorTranslator.FromHtml("#C0C0C0")
Case ConsoleColor.Green
Return ColorTranslator.FromHtml("#00FF00")
Case ConsoleColor.Magenta
Return Color.Magenta
Case ConsoleColor.Red
Return Color.Red
Case ConsoleColor.White
Return Color.White
Case Else
Return Color.Yellow
End Select
End Function
End Module
允许,
Dim result As Drawing.Color = ConsoleColor.Red.DrawingColor()
答案 2 :(得分:1)
只是改编了@Jodrell解决方案
''' <summary>
''' Generates a random QB color.
''' </summary>
''' <returns>Color.</returns>
Public Shared Function QB() As Color
Dim Rand As New Random
Dim c As Color = Color.FromName([Enum].Parse(GetType(ConsoleColor),
Rand.Next(0, 15)).ToString)
Select Case c.IsKnownColor
' Fix for the 'Consolecolor.DarkYellow' value which doesn't have color information.
Case False
Return Color.FromArgb(255, 128, 128, 0)
Case Else
Return c
End Select
End Function