SecureString Конструкторы

Определение

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

Перегрузки

Имя Описание
SecureString()

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

SecureString(Char*, Int32)

Инициализирует новый экземпляр SecureString класса из субаррей Char объектов.

Этот конструктор не соответствует CLS. Альтернатива, совместимая с CLS, является SecureString().

SecureString()

Исходный код:
SecureString.cs
Исходный код:
SecureString.cs
Исходный код:
SecureString.cs
Исходный код:
SecureString.cs
Исходный код:
SecureString.cs

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

public:
 SecureString();
public SecureString();
Public Sub New ()

Исключения

Произошла ошибка при защите или отмене защиты значения этого экземпляра.

Эта операция не поддерживается на этой платформе.

Примеры

В следующем примере конструктор по умолчанию (или без параметров) используется для создания экземпляра нового SecureString объекта. Затем он вызывает AppendChar метод, чтобы добавить в него массив символов.

using System;
using System.Security;

public class Example
{
   public static void Main()
   {
      // Define the string value to assign to a new secure string.
      char[] chars = { 't', 'e', 's', 't' };
      // Instantiate the secure string.
      SecureString testString = new SecureString();
      // Assign the character array to the secure string.
      foreach (char ch in chars)
         testString.AppendChar(ch);      
      // Display secure string length.
      Console.WriteLine("The length of the string is {0} characters.", 
                        testString.Length);
      testString.Dispose();
   }
}
// The example displays the following output:
//      The length of the string is 4 characters.
Imports System.Security

Module Example
   Public Sub Main()
      ' Define the string value to assign to a new secure string.
      Dim chars() As Char = { "t"c, "e"c, "s"c, "t"c }
      ' Instantiate the secure string.
      Dim testString As SecureString = New SecureString()
      ' Assign the character array to the secure string.
      For Each ch As char In chars
         testString.AppendChar(ch)
      Next         
      ' Display secure string length.
      Console.WriteLine("The length of the string is {0} characters.", _ 
                        testString.Length)
      testString.Dispose()
   End Sub
End Module
' The example displays the following output:
'      The length of the string is 4 characters.

В следующем примере создается SecureString объект из значения String объекта.

using System;
using System.Security;

public class Example
{
   public static void Main()
   {
      // Define the string value to be assigned to the secure string.
      string initString = "TestString";
      // Instantiate the secure string.
      SecureString testString = new SecureString();
      // Use the AppendChar method to add each char value to the secure string.
      foreach (char ch in initString)
         testString.AppendChar(ch);
         
      // Display secure string length.
      Console.WriteLine("The length of the string is {0} characters.", 
                        testString.Length);
      testString.Dispose();
   }
}
// The example displays the following output:
//      The length of the string is 10 characters.
Imports System.Security

Module Example
   Public Sub Main()
      ' Define the string value to be assigned to the secure string.
      Dim initString As String = "TestString"
      ' Instantiate the secure string.
      Dim testString As SecureString = New SecureString()
      ' Use the AppendChar method to add each char value to the secure string.
      For Each ch As Char In initString
         testString.AppendChar(ch)
      Next   
      ' Display secure string length.
      Console.WriteLine("The length of the string is {0} characters.", _ 
                        testString.Length)
      testString.Dispose()
   End Sub
End Module
' The example displays the following output:
'      The length of the string is 10 characters.

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

SecureString(Char*, Int32)

Исходный код:
SecureString.cs
Исходный код:
SecureString.cs
Исходный код:
SecureString.cs
Исходный код:
SecureString.cs
Исходный код:
SecureString.cs

Внимание

Этот API несовместим с CLS.

Инициализирует новый экземпляр SecureString класса из субаррей Char объектов.

Этот конструктор не соответствует CLS. Альтернатива, совместимая с CLS, является SecureString().

public:
 SecureString(char* value, int length);
[System.CLSCompliant(false)]
public SecureString(char* value, int length);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public SecureString(char* value, int length);
[<System.CLSCompliant(false)>]
new System.Security.SecureString : nativeptr<char> * int -> System.Security.SecureString
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
new System.Security.SecureString : nativeptr<char> * int -> System.Security.SecureString

Параметры

value
Char*

Указатель на массив объектов Char.

length
Int32

Количество элементов для value включения в новый экземпляр.

Атрибуты

Исключения

value равно null.

length меньше нуля или больше 65 536.

Произошла ошибка при защите или отмене защиты значения этой безопасной строки.

Эта операция не поддерживается на этой платформе.

Примеры

В следующем примере создается экземпляр нового SecureString объекта путем передачи конструктора указателя на массив символов.

using System;
using System.Security;

public class Example
{
   unsafe public static void Main()
   {
      SecureString testString;
      // Define the string value to assign to a new secure string.
      char[] chars = { 't', 'e', 's', 't' };

      // Instantiate a new secure string.
      fixed(char* pChars = chars)
      {
         testString = new SecureString(pChars, chars.Length);
      }
      // Display secure string length.
      Console.WriteLine("The length of the string is {0} characters.", 
                        testString.Length);
      testString.Dispose();
   }
}
// The example displays the following output:
//      The length of the string is 4 characters.

Комментарии

Этот конструктор инициализирует новый SecureString объект в число символов, value указанных lengthв; значение экземпляра затем шифруется.

В C#этот конструктор определяется только в контексте небезопасного кода.

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