如何在 COM Interop 程式設計中使用已編製索引的屬性

索引的屬性是與其他 C# 功能 (例如具名和選擇性引數、新類型 (dynamic) 和內嵌類型資訊) 搭配運作,以加強 Microsoft Office 程式設計。

重要

VSTO (Visual Studio Tools for Office) 需依賴 .NET Framework。 COM 增益集也可以使用 .NET Framework 撰寫。 無法使用 .NET Core 與 .NET 5+、最新版本的 .NET 來建立 Office 增益集。 這是因為 .NET Core/.NET 5+ 無法與相同處理序中的 .NET Framework 一起執行,而且可能會導致增益集載入失敗。 您可以繼續使用 .NET Framework 為 Office 撰寫 VSTO 和 COM 增益集。 Microsoft 不會更新 VSTO 或 COM 增益集平台,以使用 .NET Core 或 .NET 5+。 您可以利用 .NET Core 與 .NET 5+ (包括 ASP.NET Core) 來建立 Office Web 增益集的伺服器端。

在舊版 C# 中,只有在 get 方法沒有參數以及 set 方法只有一個值參數時,才能將方法存取為屬性。 不過,並非所有 COM 屬性都符合這些限制。 例如,Excel Range[] 屬性具有需要範圍名稱參數的 get 存取子。 在過去,因為您無法直接存取 Range 屬性,所以必須改為使用 get_Range 方法,如下列範例所示。

// Visual C# 2008 and earlier.
var excelApp = new Excel.Application();
// . . .
Excel.Range targetRange = excelApp.get_Range("A1", Type.Missing);

索引的屬性可讓您改為撰寫下列程式碼︰

// Visual C# 2010.
var excelApp = new Excel.Application();
// . . .
Excel.Range targetRange = excelApp.Range["A1"];

先前的範例也會使用選擇性引數功能,以讓您略過 Type.Missing

索引的屬性可讓您改為撰寫下列程式碼。

// Visual C# 2010.
targetRange.Value = "Name";

您無法建立自己本身的編製過索引的屬性。 這個功能僅支援使用現有已編製過索引的屬性。

範例

下列程式碼顯示完整範例。 如需如何設定存取 Office API 之專案的詳細資訊,請參閱如何:使用 C# 功能存取 Office Interop 物件

// You must add a reference to Microsoft.Office.Interop.Excel to run
// this example.
using System;
using Excel = Microsoft.Office.Interop.Excel;

namespace IndexedProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            CSharp2010();
        }

        static void CSharp2010()
        {
            var excelApp = new Excel.Application();
            excelApp.Workbooks.Add();
            excelApp.Visible = true;

            Excel.Range targetRange = excelApp.Range["A1"];
            targetRange.Value = "Name";
        }

        static void CSharp2008()
        {
            var excelApp = new Excel.Application();
            excelApp.Workbooks.Add(Type.Missing);
            excelApp.Visible = true;

            Excel.Range targetRange = excelApp.get_Range("A1", Type.Missing);
            targetRange.set_Value(Type.Missing, "Name");
            // Or
            //targetRange.Value2 = "Name";
        }
    }
}

另請參閱