2

我有一个需要在运行时加载 dll 的应用程序,并且我想在动态加载的 DLL 中创建一些自定义属性,因此当它加载时,我可以在尝试使用它之前检查以确保某些属性具有某些值。

我创建一个这样的属性

using System;
[AttributeUsage(AttributeTargets.Class)]
public class ValidReleaseToApp : Attribute
{
    private string ReleaseToApplication;

    public ValidReleaseToApp(string ReleaseToApp)
    {
        this.ReleaseToApplication = ReleaseToApp;
    }
} 

在动态加载的 DLL 中,我设置了这样的属性

[ValidReleaseToApp("TheAppName")]
public class ClassName : IInterfaceName
etc... etc....

但是当我尝试读取属性值时,我只得到属性名称“ValidReleaseToApp”如何检索值“TheAppName”?

Assembly a = Assembly.LoadFrom(PathToDLL);
Type type = a.GetType("Namespace.ClassName", true);
System.Reflection.MemberInfo info = type;
var attributes = info.GetCustomAttributes(true);
MessageBox.Show(attributes[0].ToString());

更新:

由于我在运行时动态加载 dll,因此属性的定义无效。到主应用程序。因此,当我尝试按照建议执行以下操作时

string value = ((ValidReleaseToApp)attributes[0]).ReleaseToApplication;
MessageBox.Show(value);

我收到这个错误

The type or namespace name 'ValidReleaseToApp' could not be found

更新2:

好的,问题是我在动态加载的 DLL 的项目中定义了属性。一旦我将属性定义移动到它自己的项目中,并将对该项目的引用添加到主项目和动态加载的 dll 中,建议的代码就起作用了。

4

2 回答 2

4

这应该可行,我现在没有一个例子在我面前,但它看起来是正确的。您基本上跳过了公开您想要访问的属性以及转换为属性类型以检索该属性的步骤。

using System;
[AttributeUsage(AttributeTargets.Class)]
public class ValidReleaseToApp : Attribute
{
    private string _releaseToApplication;
    public string ReleaseToApplication { get { return _releaseToApplication; } }

    public ValidReleaseToApp(string ReleaseToApp)
    {
        this._releaseToApplication = ReleaseToApp;
    }
} 


Assembly a = Assembly.LoadFrom(PathToDLL);
Type type = a.GetType("Namespace.ClassName", true);
System.Reflection.MemberInfo info = type;
var attributes = info.GetCustomAttributes(true);
if(attributes[0] is ValidReleaseToApp){
   string value = ((ValidReleaseToApp)attributes[0]).ReleaseToApplication ;
   MessageBox.Show(value);
}
于 2010-07-23T15:44:19.440 回答
0

拥有自定义属性后,您可以将它们转换为属性类的实例并访问它们的属性:

object[] attributes = info.GetCustomAttributes(typeof(ValidReleaseToAppAttribute), true);
ValidReleaseToAppAttrigute attrib = attributes[0] as ValidReleaseToAppAttribute;
MessageBox.Show(attrib.ReleaseToApp);
于 2010-07-23T15:46:31.090 回答