2011-10-20 3 views
5

Tôi có đoạn code sau đây trong ứng dụng của tôi:Mã Phân tích CA1060 Fix

[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); 

Tôi nhận được cảnh báo sau đây từ Phân tích Mã (FxCop):

CA1060: Microsoft.Design: Bởi vì nó là một phương thức P/Invoke, 'IconHelper.GetWindowLong (IntPtr, int)' nên được định nghĩa trong một lớp có tên là NativeMethods, SafeNativeMethods hoặc UnsafeNativeMethods.

Ai đó có thể cho tôi biết tôi nên đưa họ vào lớp nào? Tôi không biết liệu đó là Gốc, An toàn hoặc Không an toàn.

+0

thể trùng lặp của [Làm thế nào để biết nếu phương pháp tự nhiên là an toàn/không an toàn?] (Http://stackoverflow.com/questions/4511418/how-to-know-if-native -method-an toàn-không an toàn) – dtb

+2

[FAQ: Làm cách nào để khắc phục vi phạm MovePInvokesToNativeMethodsClass?] (http://blogs.msdn.com/b/codeanalysis/archive/2007/01/14/faq-how- do-i-fix-a-vi phạm-of-movepinvokestonativemethodsclass.aspx) – dtb

Trả lời

4

Hãy thử di chuyển tất cả chúng vào một lớp NativeMethod, nó sẽ giải quyết vấn đề

Mã của bạn sẽ trông như thế này sau khi sửa chữa nó

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); 
} 

Hãy nhớ để thay đổi tất cả những nơi mà bạn đang gọi những phương thức này

Trước khi thay đổi

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

nên

+1

Các phương pháp không nên được công khai? – JohnSaps

+0

Trong các phương pháp mã trên phải là "nội bộ". Cảnh báo cảnh báo "Công khai" "Không được hiển thị các yêu cầu P/CA CA1401" – Sielu