如何读取程序集属性 [英] How to read assembly attributes

查看:9
本文介绍了如何读取程序集属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,如何读取在 AssemblyInfo.cs 中设置的属性:

In my program, how can I read the properties set in 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("")]

我想向我的程序的用户显示其中一些值,所以我想知道如何从主程序和我正在使用的组件程序集中加载它们.

I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using.

推荐答案

这相当容易.你必须使用反射.您需要一个Assembly 实例来表示具有您要读取的属性的程序集.一个简单的方法是这样做:

This is reasonably easy. You have to use reflection. You need an instance of Assembly that represents the assembly with the attributes you want to read. An easy way of getting this is to do:

typeof(MyTypeInAssembly).Assembly

然后你可以这样做,例如:

Then you can do this, for example:

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

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

引用 attribute.Product 现在将为您提供传递给 AssemblyInfo.cs 中的属性的值.当然,如果您查找的属性可能出现多次,您可能会在 GetCustomAttributes 返回的数组中获得多个实例,但这对于您希望检索的程序集级属性通常不是问题.

Referencing attribute.Product will now give you the value you passed to the attribute in your AssemblyInfo.cs. Of course, if the attribute you look for can occur more than once, you may get multiple instances in the array returned by GetCustomAttributes, but this is not usually an issue for assembly level attributes like the ones you hope to retrieve.

这篇关于如何读取程序集属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆