代码分析CA1060修复

时间:2011-10-20 14:25:33

标签: c# code-analysis fxcop

我的应用程序中有以下代码:

[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hwnd, int index);

[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
               int x, int y, int width, int height, uint flags);

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hwnd, uint msg,
               IntPtr wParam, IntPtr lParam);

我从代码分析(FxCop)收到以下警告:

  

CA1060:Microsoft.Design:因为它是P / Invoke方法,   应该在类中定义'IconHelper.GetWindowLong(IntPtr,int)'   命名为NativeMethods,SafeNativeMethods或UnsafeNativeMethods。

有人可以告诉我应该把他们放进哪个班级吗?我不知道它是Native,SafeNative还是UnsafeNative。

3 个答案:

答案 0 :(得分:9)

您可以在此处获得有关此警告的详细信息:http://msdn.microsoft.com/en-us/library/ms182161.aspx。简而言之:

  

对于大多数应用程序,将P / Invokes移动到名为NativeMethods的新类就足够了。

答案 1 :(得分:4)

尝试将它们全部移动到NativeMethod类中,它将解决问题

修复后,您的代码应如下所示

public class NativeMethods {
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hwnd, int index);

[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
               int x, int y, int width, int height, uint flags);

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hwnd, uint msg,
               IntPtr wParam, IntPtr lParam);
}

请记住更改您调用这些方法的所有地方

改变之前

SendMessage(IntPtr hwnd, uint msg,IntPtr wParam, IntPtr lParam)

应该是

NativeMethods.SendMessage(IntPtr hwnd, uint msg,IntPtr wParam, IntPtr lParam)

答案 2 :(得分:0)

您可以通过定义

取消显示此警告
function getMembersInDB() {
  let membersObject = {prop1: 1, prop2: 2, prop3: 3};
  let membersListWait = [];
  let membersList = [];

  Object.keys(membersObject).map(async (key) => {
      await sleep(1000);
      membersListWait.push(membersObject[key]);
  });

  Object.keys(membersObject).map(async (key) => {
      membersList.push(membersObject[key]);
  });

  console.log(membersListWait) // prints "[]"
  console.log(membersList) // prints "[1, 2, 3]"
}

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}   

getMembersInDB()

在配置文件(.csproj文件)中。