简体   繁体   English

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

[英]Generating warnings for Int32 to Int64 casts

Is there a way to generate compile time warnings for implicit int to long conversions? 有没有办法为隐式intlong转换生成编译时警告? (An answer that involves a static analysis tool such as FxCop would be fine.) (答案涉及静态分析工具,如FxCop会很好。)

Casting an int to a long is obviously a safe operation, but say we have a library that used to have int values for its identifiers and which is now upgraded to use long values for all of them. int转换为long显然是一个安全的操作,但是我们说我们有一个库,它曾经为其标识符提供了int值,现在已升级为使用所有这些值的long值。

Now, the client code needs to be updated accordingly. 现在,客户端代码需要相应更新。 Because if the client is supplying an Int32 argument to a method that expects Int64 - it is very possible that the client code needs to be updated. 因为如果客户端向期望Int64的方法提供Int32参数 - 很可能需要更新客户端代码。

An example scenario would be the following: 示例场景如下:

private void OnProcessGizmoClick()
{
    int gizmoId = 2;

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

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

I think that the best way would be to overload the method with an Int32 parameter input, which internally could just perform the cast to Int64 - but your overloaded method could be marked as Deprecated. 我认为最好的方法是使用Int32参数输入重载该方法,该输入在内部只能执行强制转换为Int64 - 但您的重载方法可能被标记为已弃用。

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

Then Visual Studio will see both versions, and use the Int32 declaration which would give a deprecated warning. 然后Visual Studio将看到两个版本,并使用Int32声明,该声明将给出不推荐的警告。

If in a later release, or for certain methods that you absolutely don't want to be called with the Int32 parameter you were to decide that you wanted to cause a compiler error, you could also update it to the following. 如果在以后的版本中,或者对于您绝对不希望使用Int32参数调用的某些方法,您决定是否要导致编译器错误,您还可以将其更新为以下内容。

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

Define your own type with implicit conversion from both long and int ; 使用longint隐式转换来定义自己的类型; make warning on implicit conversion from int like: 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