InternalsVisibleToAttribute(String) Конструктор

Определение

Инициализирует новый экземпляр класса InternalsVisibleToAttribute с именем заданной дружественной сборки.

public:
 InternalsVisibleToAttribute(System::String ^ assemblyName);
public InternalsVisibleToAttribute (string assemblyName);
new System.Runtime.CompilerServices.InternalsVisibleToAttribute : string -> System.Runtime.CompilerServices.InternalsVisibleToAttribute
Public Sub New (assemblyName As String)

Параметры

assemblyName
String

Имя дружественной сборки.

Примеры

Подписанные сборки

В следующем примере атрибут используется InternalsVisibleToAttribute для создания метода, именованного internal AppendDirectorySeparator в подписанной сборке, видимой для другой подписанной сборки. Он определяет FileUtilities класс, включающий внутренний AppendDirectorySeparator метод. Атрибут InternalsVisibleToAttribute применяется к сборке, содержащей FileUtilities класс. Атрибут позволяет сборке с именем Friend1 получить доступ к этому внутреннему члену.

//
// The source code should be saved in a file named Example1.cs. It 
// can be compiled at the command line as follows:
//
//    csc /t:library /keyfile:<snkfilename> Assembly1.cs
//
// The public key of the Friend1 file should be changed to the full
// public key stored in your strong-named key file.
//
using System;
using System.IO;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Friend1, PublicKey=002400000480000094" + 
                              "0000000602000000240000525341310004000" +
                              "001000100bf8c25fcd44838d87e245ab35bf7" +
                              "3ba2615707feea295709559b3de903fb95a93" +
                              "3d2729967c3184a97d7b84c7547cd87e435b5" +
                              "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" +
                              "712da72eec2533dc00f8529c3a0bbb4103282" +
                              "f0d894d5f34e9f0103c473dce9f4b457a5dee" +
                              "fd8f920d8681ed6dfcb0a81e96bd9b176525a" +
                              "26e0b3")]

public class FileUtilities
{
   internal static string AppendDirectorySeparator(string dir)
   {
      if (! dir.Trim().EndsWith(Path.DirectorySeparatorChar.ToString()))
         return dir.Trim() + Path.DirectorySeparatorChar;
      else
         return dir;
   }
}
'
' The source code should be saved in a file named Example1.cs. It 
' can be compiled at the command line as follows:
'
'    vbc Assembly1.vb /t:library /keyfile:<snkfilename> 
'
' The public key of the Friend1 file should be changed to the full
' public key stored in your strong-named key file.
'
Imports System.IO
Imports System.Runtime.CompilerServices

<Assembly:InternalsVisibleTo("Friend1, PublicKey=002400000480000094" + _
                             "0000000602000000240000525341310004000" + _
                             "001000100bf8c25fcd44838d87e245ab35bf7" + _
                             "3ba2615707feea295709559b3de903fb95a93" + _
                             "3d2729967c3184a97d7b84c7547cd87e435b5" + _
                             "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" + _
                             "712da72eec2533dc00f8529c3a0bbb4103282" + _
                             "f0d894d5f34e9f0103c473dce9f4b457a5dee" + _
                             "fd8f920d8681ed6dfcb0a81e96bd9b176525a" + _
                             "26e0b3")>

Public Class FileUtilities
   Friend Shared Function AppendDirectorySeparator(dir As String) As String
      If Not dir.Trim().EndsWith(Path.DirectorySeparatorChar) Then
         Return dir.Trim() + Path.DirectorySeparatorChar
      Else
         Return dir
      End If   
   End Function
End Class

Если следующий пример компилируется в сборку со строгим именем Friend1, он может успешно вызвать FileUtilities.AppendDirectorySeparator метод, даже если метод является внутренним для сборки Assembly1 . Обратите внимание, что при компиляции в C# из командной строки необходимо использовать параметр компилятора /out , чтобы убедиться, что имя дружественной сборки доступно при привязке компилятора к внешним ссылкам.

//
// The assembly that exposes its internal types to this assembly should be
// named Assembly1.dll.
//
// The public key of this assembly should correspond to the public key
// specified in the class constructor of the InternalsVisibleTo attribute in the
// Assembly1 assembly.
//
#using <Assembly1.dll> as_friend

using namespace System;

void main()
{
   String^ dir = L"C:\\Program Files";
   dir = FileUtilities::AppendDirectorySeparator(dir);
   Console::WriteLine(dir);
}
// The example displays the following output:
//       C:\Program Files\
//
// The source code should be saved in a file named Friend1.cs. It 
// can be compiled at the command line as follows:
//
//    csc /r:Assembly1.dll /keyfile:<snkfilename> /out:Friend1.dll Friend1.cs
//
// The public key of the Friend1 assembly should correspond to the public key
// specified in the class constructor of the InternalsVisibleTo attribute in the
// Assembly1 assembly.
//
using System;

public class Example
{
   public static void Main()
   {
      string dir = @"C:\Program Files";
      dir = FileUtilities.AppendDirectorySeparator(dir);
      Console.WriteLine(dir);
   }
}
// The example displays the following output:
//       C:\Program Files\
'
' The source code should be saved in a file named Friend1.vb. It 
' can be compiled at the command line as follows:
'
'    vbc Friend1.vb /r:Assembly1.dll /keyfile:<snkfilename> 
'
' The public key of the Friend1 assembly should correspond to the public key
' specified in the class constructor of the InternalsVisibleTo attribute in the
' Assembly1 assembly.
'
Module Example
   Public Sub Main()
      Dim dir As String = "C:\Program Files"
      dir = FileUtilities.AppendDirectorySeparator(dir)
      Console.WriteLine(dir)
   End Sub
End Module
' The example displays the following output:
'       C:\Program Files\

В следующем примере атрибут используется InternalsVisibleToAttribute для создания internal члена неподписаемой сборки, видимой для другой сборки без знака. Атрибут гарантирует, что internal StringLib.IsFirstLetterUpperCase метод в именованной UtilityLib сборке виден коду в сборке с именем Friend2. Ниже приведен исходный код для UtilityLib.dll.

using System;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleToAttribute("Friend2")]

namespace Utilities.StringUtilities
{
   public class StringLib
   {
      internal static bool IsFirstLetterUpperCase(String s)
      {
         string first = s.Substring(0, 1);
         return first == first.ToUpper();
      }
   }
}

Imports System.Runtime.CompilerServices

<assembly: InternalsVisibleTo("Friend2")>

Namespace Utilities.StringUtilities
   Public Class StringLib
      Friend Shared Function IsFirstLetterUpperCase(s As String) As Boolean
         Dim first As String = s.Substring(0, 1)
         Return first = first.ToUpper()
      End Function
   End Class
End Namespace

Неподписанные сборки

В следующем примере приведен исходный код сборки Friend2 . Обратите внимание, что при компиляции в C# из командной строки необходимо использовать параметр компилятора /out , чтобы убедиться, что имя дружественной сборки доступно при привязке компилятора к внешним ссылкам.

#using <UtilityLib.dll> as_friend

using namespace System;
using namespace Utilities::StringUtilities;

void main()
{
   String^ s = "The Sign of the Four";
   Console::WriteLine(StringLib::IsFirstLetterUpperCase(s));
}
using System;
using Utilities.StringUtilities;

public class Example
{
   public static void Main()
   {
      String s = "The Sign of the Four";
      Console.WriteLine(StringLib.IsFirstLetterUpperCase(s));
   }
}
Imports Utilities.StringUtilities

Module Example
   Public Sub Main()
      Dim s As String = "The Sign of the Four"
      Console.WriteLine(StringLib.IsFirstLetterUpperCase(s))
   End Sub
End Module

Комментарии

Конструктор InternalsVisibleToAttribute определяет другую сборку, которая является сборкой, которая имеет доступ к внутренним и закрытым защищенным типам и членам текущей сборки.

Как текущая сборка, так и другая сборка должны быть без знака, или обе сборки должны быть подписаны строгим именем. (Дополнительные сведения о сборках со строгими именами см. в статье "Создание и использование сборок со строгими именами".) Если оба варианта не подписаны, assemblyName аргумент состоит из имени дружественной сборки, указанной без пути к каталогу или расширения файла. Если оба подписываются, assemblyName состоит из имени дружественной сборки без пути к каталогу или расширения имени файла, а также полного открытого ключа (но не маркера открытого ключа). Другие компоненты строгого имени, такие как те, которые предоставляют сведения о языке и региональных параметрах, версии или архитектуре процессора, нельзя указать в аргументе assemblyName .

Важно!

При использовании компилятора C# для компиляции дружественной сборки необходимо явно указать имя выходного файла (.exe или .dll) с помощью параметра компилятора /out . Это необходимо потому, что компилятор еще не создал имя сборки, формируемой во время привязки к внешним ссылкам. Параметр компилятора /out является необязательным для компилятора Visual Basic, а соответствующий параметр компилятора -out или -o не следует использовать при компиляции дружественных сборок с компилятором F#.

Вы можете использовать Sn.exe (средство строгого имени) для получения полного открытого ключа из файла строго именованного ключа (SNK). Для этого выполните следующие действия.

  1. Извлеките открытый ключ из файла ключа со строгим именем в отдельный файл:

    Sn -p snk_file outfile

  2. Отображение полного открытого ключа в консоли:

    Sn - tpoutfile

  3. Скопируйте и вставьте полное значение открытого ключа в исходный код.

Дополнительные сведения об использовании атрибута InternalsVisibleToAttribute см. в следующих статьях:

Применяется к