c# - VB 到 C# 属性到 int 转换的转换

标签 c# vb.net properties

原创(作品):

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/

相关文章:

c# - WCF Restful 网络服务 |发送图像

vb.net - 无法完全清除 Winforms ComboBox 中的项目

javascript - 在 asp.net 和 vb.net web 应用程序中保存后如何关闭弹出窗体

iphone - 自动释放和属性

c# - 如何禁用所有 WPF 应用程序的虚拟键盘?

c# - 如何在 C# 的 GridView 中进行多行选择

.net - 缩小编码为 Base64 的 float 据字节

c# - 自动属性初始化 IL 指令顺序

c# - 如果我的类有一个带有用于存储的私有(private)字段的属性,我应该使用私有(private)字段还是属性在构造函数中对其进行初始化?

c# - 如何使用 C# 启动数据库事务,在 MySQL 上运行多个查询然后提交或回滚?