繁体   English   中英

生成Int32到Int64强制转换的警告

[英]Generating warnings for Int32 to Int64 casts

有没有办法为隐式intlong转换生成编译时警告? (答案涉及静态分析工具,如FxCop会很好。)

int转换为long显然是一个安全的操作,但是我们说我们有一个库,它曾经为其标识符提供了int值,现在已升级为使用所有这些值的long值。

现在,客户端代码需要相应更新。 因为如果客户端向期望Int64的方法提供Int32参数 - 很可能需要更新客户端代码。

示例场景如下:

private void OnProcessGizmoClick()
{
    int gizmoId = 2;

    // I want the following usage to generate warnings:
    GizmoFactoryInstance.ProcessGizmo(gizmoId);
}

// Library code
public void ProcessGizmo(long gizmoId);

我认为最好的方法是使用Int32参数输入重载该方法,该输入在内部只能执行强制转换为Int64 - 但您的重载方法可能被标记为已弃用。

[Obsolete("Please use an Int64 for your identifier instead")]

然后Visual Studio将看到两个版本,并使用Int32声明,该声明将给出不推荐的警告。

如果在以后的版本中,或者对于您绝对不希望使用Int32参数调用的某些方法,您决定是否要导致编译器错误,您还可以将其更新为以下内容。

[Obsolete("Please use an Int64 for your identifier instead", true)]

使用longint隐式转换来定义自己的类型; int隐式转换发出警告:

public struct GizmoInteger
{
  private long m_Value;
  private GizmoInteger(long value)
  {
    m_Value = value;
  }

  [Obsolete("Use long instead")]
  public static implicit operator GizmoInteger(int value)
  {
    return new GizmoInteger(value);
  }

  public static implicit operator GizmoInteger(long value)
  {
    return new GizmoInteger(value);
  }
}

void Foo(GizmoInteger i)
{
}

// warning
Foo(4);
// OK
Foo(4L);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM