Dot-Net

如何將 GUID 作為屬性參數?

  • November 28, 2008

我需要一些屬性類中的 Guid 屬性,如下所示:

public class SomeAttribute : Attribute {
   private Guid foreignIdentificator;
   public Guid ForeignIdentificator {
       get { return this.foreignIdentificator; }
       set { this.foreignIdentificator = value; }
   }
}

但是在屬性定義中,我只能使用原始類型,它們是常量(我理解為什麼,這讓我很有意義)。解決方法可以將“ForeignIdentificator”定義為字元串,並在執行時創建 Guid:

public class SomeAttribute : Attribute {
   private string foreignIdentificator;
   public string ForeignIdentificator {
       get { return this.foreignIdentificator; }
       set { this.foreignIdentificator = value; }
   }
   public Guid ForeignIdentificatorGuid {
       get { return new Guid( ForeignIdentificator ); }
   }
}

Unahppily 我放鬆檢查類型安全。“ForeignIdentificator”屬性可以包含任何字元串值,並且在創建 Guid 期間將在執行時拋出異常,而不是在編譯時。

我知道編譯器會檢查“System.Runtime.InteropServices.GuidAttribute”的字元串值以獲取“Guid 兼容性”。這個檢查正是我需要的,但我不知道這個檢查是我在編譯器中硬編碼還是我可以明確定義(以及如何)。

您是否知道某種方式,如何確保“Guid 兼容性”檢查屬性?或者其他方式,如何在屬性中達到類型安全的 Guid 定義?謝謝。

我過去遇到過你的確切問題。我們只是要求他們將 GUID 作為字元串傳遞…這是 VS GUID 生成器工具提供給我們的預設方式 (*F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4)。我們基本上做了你所做的。我們在外掛架構中使用它,因此我們的客戶一直是使用該介面的人。如果你看看微軟在他們需要做同樣的事情時做了什麼,他們就會這樣做。

這樣做沒有問題。不止一次,我們是否將其視為該領域的問題。

不過,您可能希望將該字元串欄位命名為 GUID,以免混淆您的消費者。添加一些文件以防他們不知道它需要採用什麼格式。

當我看到這個時,我有同樣的反應……但後來我繼續前進,因為似乎沒有類型安全的解決方案。

引用自:https://stackoverflow.com/questions/325756