原创(作品):
Dim fnt As Drawing.Font = New Drawing.Font( _
rtf.SelectionFont.FontFamily, _
rtf.SelectionFont.Size, _
DirectCast(rtf.SelectionFont.Style _
+ If(rtf.SelectionFont.Underline, _
-Drawing.FontStyle.Underline, _
Drawing.FontStyle.Underline), _
Drawing.FontStyle) _
)
translation () 无法将 FontStyle 转换为 int:
System.Drawing.Font fnt = new System.Drawing.Font(
rtf_Renamed.SelectionFont.FontFamily,
rtf_Renamed.SelectionFont.Size,
(System.Drawing.FontStyle)(
rtf_Renamed.SelectionFont.Style
+ rtf_Renamed.SelectionFont.Underline
? -System.Drawing.FontStyle.Underline //cannot cast to int
: System.Drawing.FontStyle.Underline
)
);
那么如何将这些 .NET 属性转换为它们的数值呢?
最佳答案
我相信您的代码试图做的是在原始代码没有下划线的情况下添加下划线,否则将其删除。
但是FontStyle应该被位掩码,以便切换下划线部分。 您不应该执行算术加法和减法,因为如果原始样式设置了任何其他属性,这将无法正常工作。
您必须执行 DirectCast 的事实是一个警钟,表明某些事情可能不正确。
您的 VB 代码应如下所示:
Dim fnt As Drawing.Font = New Drawing.Font(rtf.SelectionFont.FontFamily,
rtf.SelectionFont.Size,
rtf.SelectionFont.Style XOr FontStyle.Underline)
所以 C# 等价物应该是这样的:
Drawing.Font fnt = new Drawing.Font(rtf.SelectionFont.FontFamily,
rtf.SelectionFont.Size,
rtf.SelectionFont.Style ^ FontStyle.Underline);
有关此的一些背景,请参阅此问题:How to set multiple FontStyles when instantiating a font?
关于c# - VB 到 C# 属性到 int 转换的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563900/