使用 protobuf 型別

由於 Google Ads API 使用 proto3 做為預設的酬載格式,因此使用 .NET 用戶端程式庫時,請務必瞭解一些通訊協定緩衝區慣例和型別。

選填欄位

Google Ads API 中的許多欄位都標示為 optional。這樣一來,您就能區分欄位值為空的情況,以及伺服器未傳回欄位值的情況。這些欄位的行為與一般屬性類似,但也會提供額外方法來清除欄位,以及檢查欄位是否已設定。

舉例來說,Campaign 物件的 Name 欄位標示為 optional,因此您可以使用下列方法處理這個欄位:

// Get the name.
string name = campaign.Name;

// Set the name.
campaign.Name = name;

// Check if the campaign object has the name field set.
bool hasName = campaign.HasName();

// Clear the name field. Use this method to exclude the Name field from
// being sent to the server in a subsequent API call.
campaign.ClearName();

// Set the campaign name to an empty string value. This value will be
// sent to the server if you use this object in a subsequent API call.
campaign.Name = "";

// This throws a runtime ArgumentNullException. Use ClearName() instead.
campaign.Name = null;

重複欄位

在 Google Ads API 中,欄位陣列會以唯讀的RepeatedField表示。

舉例來說,廣告活動的 url_custom_parameters 欄位是重複欄位,因此在 .NET 用戶端程式庫中,會以唯讀的 RepeatedField<CustomParameter> 表示。RepeatedField<T> 會實作 IList<T> 介面。

填入 RepeatedField 屬性的方式有兩種:

AddRange 方法

Campaign campaign = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    Status = CampaignStatus.Paused,
};

// Add values to UrlCustomParameters using the AddRange method.
campaign.UrlCustomParameters.AddRange(new CustomParameter[]
{
    new CustomParameter { Key = "season", Value = "christmas" },
    new CustomParameter { Key = "promocode", Value = "NY123" }
});

集合初始設定式語法

// Option 1: Initialize the field directly.
Campaign campaign = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    Status = CampaignStatus.Paused,
    // Directly initialize the field.
    UrlCustomParameters =
    {
        new CustomParameter { Key = "season", Value = "christmas" },
        new CustomParameter { Key = "promocode", Value = "NY123" }
    }
};

// Option 2: Initialize using an intermediate variable.
CustomParameter[] parameters = new CustomParameter[]
{
    new CustomParameter { Key = "season", Value = "christmas" },
    new CustomParameter { Key = "promocode", Value = "NY123" }
};

Campaign campaign1 = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    Status = CampaignStatus.Paused,
    // Initialize from an existing array.
    UrlCustomParameters = { parameters }
};

Oneof 欄位

Google Ads API 中的部分欄位標示為 oneof 欄位,表示該欄位可保留不同型別的值,但一次只能保留一個值。oneof 欄位類似於 C 程式設計語言中的聯集型別。

.NET 程式庫會為可保留在 oneof 欄位中的每個值類型提供一個屬性,藉此實作 oneof 欄位,所有屬性都會更新共用的基礎儲存空間欄位。

舉例來說,廣告活動的 campaign_bidding_strategy 會標示為 oneof 欄位。這個類別的實作方式如下 (為簡潔起見,程式碼已簡化):

public sealed partial class Campaign : pb::IMessage<Campaign>
{
    object campaignBiddingStrategy_ = null;
    CampaignBiddingStrategyOneofCase campaignBiddingStrategyCase_;

    public ManualCpc ManualCpc
    {
        get
        {
            return campaignBiddingStrategyCase_ ==
                CampaignBiddingStrategyOneofCase.ManualCpc
                ? (ManualCpc)campaignBiddingStrategy_ : null;
        }
        set
        {
            campaignBiddingStrategy_ = value;
            campaignBiddingStrategyCase_ =
                CampaignBiddingStrategyOneofCase.ManualCpc;
        }
    }

    public ManualCpm ManualCpm
    {
        get
        {
            return campaignBiddingStrategyCase_ ==
                CampaignBiddingStrategyOneofCase.ManualCpm
                ? (ManualCpm)campaignBiddingStrategy_ : null;
        }
        set
        {
            campaignBiddingStrategy_ = value;
            campaignBiddingStrategyCase_ =
                CampaignBiddingStrategyOneofCase.ManualCpm;
        }
    }

    public CampaignBiddingStrategyOneofCase CampaignBiddingStrategyCase
    {
        get { return campaignBiddingStrategyCase_; }
    }
}

由於 oneof 屬性共用儲存空間,因此一項指派作業可能會覆寫先前的指派作業,導致細微的錯誤。例如:

Campaign campaign = new Campaign()
{
    ManualCpc = new ManualCpc(),
    ManualCpm = new ManualCpm()
};

在本例中,campaign.ManualCpc 為 null,因為初始化 campaign.ManualCpm 屬性會覆寫 campaign.ManualCpc 的先前初始化作業。

轉換為其他格式

轉換為 JSON 格式

您可以使用 Google.Protobuf.JsonFormatter 將 protobuf 物件轉換為 JSON 格式,反之亦然。建構需要與其他系統介接的系統時,這項功能非常實用,因為這些系統需要 JSON 或 XML 等文字型格式。

using Google.Protobuf;

GoogleAdsRow row = new GoogleAdsRow()
{
    Campaign = new Campaign()
    {
        Id = 123,
        Name = "Campaign 1",
        ResourceName = ResourceNames.Campaign(1234567890, 123)
    }
};

// Serialize to JSON and back.
string json = JsonFormatter.Default.Format(row);
row = GoogleAdsRow.Parser.ParseJson(json);

轉換為位元組

您可以使用 Google.Protobuf 將物件序列化為位元組,然後再還原。與 JSON 格式相比,二進位序列化更節省記憶體和儲存空間。

using Google.Protobuf;

GoogleAdsRow row = new GoogleAdsRow()
{
    Campaign = new Campaign()
    {
        Id = 123,
        Name = "Campaign 1",
        ResourceName = ResourceNames.Campaign(1234567890, 123)
    }
};

// Serialize to bytes and back.
byte[] bytes = row.ToByteArray();
row = GoogleAdsRow.Parser.ParseFrom(bytes);