共用方式為


CA1401:P/Invokes 不應該為可見的

型別名稱

PInvokesShouldNotBeVisible

CheckId

CA1401

分類

Microsoft.Interoperability

中斷變更

中斷

原因

公用型別中之公用或保護的方法會含有 DllImportAttribute 屬性 (也會由 Visual Basic 中的 Declare 關鍵字實作)。

規則描述

使用 DllImportAttribute 屬性所標記的方法,或在 Visual Basic 中使用 Declare 關鍵字定義的方法,都會使用平台引動服務 (Platform Invocation Service) 存取 Unmanaged 程式碼。但不得公開 (Expose) 此類方法。使這些方法保持為私用或內部,便可確保程式庫不會因為允許呼叫端存取之前無法呼叫的 Unmanaged API 而用於侵害安全性。

如何修正違規

若要修正此規則的違規情形,請變更方法的存取層級。

隱藏警告的時機

請勿隱藏此規則的警告。

範例

下列範例會宣告違反此規則的方法。

Imports System

NameSpace MSInternalLibrary

' Violates rule: PInvokesShouldNotBeVisible. 
Public Class NativeMethods
    Public Declare Function RemoveDirectory Lib "kernel32"( _
        ByVal Name As String) As Boolean 
End Class 

End NameSpace 
using System;
using System.Runtime.InteropServices;

namespace InteroperabilityLibrary
{
    // Violates rule: PInvokesShouldNotBeVisible. 
    public class NativeMethods
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern bool RemoveDirectory(string name);
    }
}