Dot-Net

如何讀取程序集屬性

  • October 9, 2008

在我的程序中,如何讀取 AssemblyInfo.cs 中設置的屬性:

[assembly: AssemblyTitle("My Product")]
[assembly: AssemblyDescription("...")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Radeldudel inc.")]
[assembly: AssemblyProduct("My Product")]
[assembly: AssemblyCopyright("Copyright @ me 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

我想向我的程序的使用者顯示其中一些值,所以我想知道如何從主程序和我正在使用的組件程序集中載入它們。

這相當容易。你必須使用反射。您需要一個 Assembly 實例,該實例代表具有您要讀取的屬性的程序集。一個簡單的方法是這樣做:

typeof(MyTypeInAssembly).Assembly

然後你可以這樣做,例如:

object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);

AssemblyProductAttribute attribute = null;
if (attributes.Length > 0)
{
  attribute = attributes[0] as AssemblyProductAttribute;
}

現在,引用attribute.Product將為您提供您傳遞給 AssemblyInfo.cs 中屬性的值。當然,如果您查找的屬性可以多次出現,您可能會在 GetCustomAttributes 返回的數組中獲得多個實例,但這對於您希望檢索的程序集級屬性通常不是問題。

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