Condividi tramite


Procedura: utilizzare un indicizzatore C# (C++/CLI)

In Visual C++ non sono presenti indicizzatori, ma proprietà indicizzate.Per utilizzare un indicizzatore C#, accedere all'indicizzatore come se fosse una proprietà indicizzata.

Per ulteriori informazioni sugli indicizzatori, vedere:

Esempio

Nel programma C# riportato di seguito viene definito un indicizzatore.

// consume_cs_indexers.cs
// compile with: /target:library
using System;
public class IndexerClass {
   private int [] myArray = new int[100]; 
   public int this [int index] {   // Indexer declaration
      get {
         // Check the index limits.
         if (index < 0 || index >= 100)
            return 0;
         else
            return myArray[index];
      }
      set {
         if (!(index < 0 || index >= 100))
            myArray[index] = value;
      }
   }
}
/*
// code to consume the indexer
public class MainClass {
   public static void Main() {
      IndexerClass b = new IndexerClass();

      // Call indexer to initialize elements 3 and 5
      b[3] = 256;
      b[5] = 1024;
      for (int i = 0 ; i <= 10 ; i++) 
         Console.WriteLine("Element #{0} = {1}", i, b[i]);
   }
}
*/

Di seguito è riportato un programma Visual C++ che utilizza l'indicizzatore.

// consume_cs_indexers_2.cpp
// compile with: /clr
#using "consume_cs_indexers.dll"
using namespace System;

int main() {
   IndexerClass ^ ic = gcnew IndexerClass;
   ic->default[0] = 21;
   for (int i = 0 ; i <= 10 ; i++)
      Console::WriteLine("Element #{0} = {1}", i, ic->default[i]);
}
  

Vedere anche

Altre risorse

Interoperabilità con altri linguaggi .NET (C++/CLI)