我正在开发一个生成节点树结构的应用程序。节点有很多类型,每种都有特定的行为和属性。我想为每个节点类型赋予属性,包括显示名称,描述和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

我还有其他方法可以将类的类型(而不是实例)与图标图像相关联吗?

最佳答案

属性构造函数的参数存储在程序集元数据中。这就对可以使用的参数类型施加了严格的限制。绝对不需要任何需要代码的东西。这就是这里失败的原因,访问Properties.Resources需要调用属性getter。

只要您要引用资源,这里就没有别的选择。我只能想到资源名称(字符串)。使用Properties.Resources.ResourceManager.GetObject()在属性构造函数中获取资源对象

关于c# - 属性可以引用嵌入式资源吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4320513/

10-11 22:28
查看更多