Eri*_*tas 5 .net c# resources attributes
我正在开发一个生成节点树结构的应用程序.有许多类型的节点,每个节点都有特定的行为和属性.我想将每个节点类型的属性包括显示名称,描述和16x16图标.
这是我创建的自定义属性的代码:
public class NodeTypeInfoAttribute : Attribute
{
    public NodeTypeInfoAttribute(string displayName, string description, System.Drawing.Image icon)
        : this(displayName, description)
    {
        this.Icon = icon;
    }
    public NodeTypeInfoAttribute(string displayName, string description, string iconPath):this(displayName,description)
    {
        String absPath;
        if (System.IO.Path.IsPathRooted(iconPath))
        {
            absPath = iconPath;
        }
        else
        {
            string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            absPath = System.IO.Path.Combine(folder, iconPath);
        }
        try
        {
            System.Drawing.Image i = System.Drawing.Image.FromFile(absPath);
        }
        catch (System.IO.FileNotFoundException)
        {
            Icon = null;
        }
    }
    public NodeTypeInfoAttribute(string displayName, string description)
    {
        this.DisplayName = displayName;
        this.Description = description;
    }
    public string DisplayName
    {
        get;
        private set;
    }
    public string Description
    {
        get;
        private set;
    }
    public System.Drawing.Image Icon
    {
        get;
        set;
    }
}
请注意,我有一个构造函数,它将Icon指定为文件路径,以及一个将图标指定为的构造函数System.Drawing.Image.
所以最终我希望能够将此属性与这样的嵌入式图像资源一起使用.
[NodeTypeInfo("My Node","Sample Description",Properties.Resources.CustomIcon)]
public class CustomNode:Node
{
...
但是,此代码返回错误
An attribute argument must be a constant expression, typeof expression or 
array creation` expression of an attribute parameter type
是否有其他方法可以将类的Type(非实例)与图标图像相关联?
属性构造函数的参数存储在程序集元数据中。这对您可以使用的参数类型施加了严格的限制。任何需要代码的东西都是绝对不支持的。这就是这里失败的原因,访问 Properties.Resources 需要调用属性 getter。
只要您想引用资源,这里就没有很好的选择。我能想到的只有资源名称、字符串。在属性构造函数中使用Properties.Resources.ResourceManager.GetObject()获取资源对象