加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

具有复杂结构的C#属性

发布时间:2020-12-16 01:43:20 所属栏目:百科 来源:网络整理
导读:编辑:看起来不可能像解决方案#2一样只有一个属性,所以我最终使用的解决方案#3不像解决方案#1那样容易出错. 我有一个属性如下: // Solution #1 (working)[Module(Name="Module1",Guid="xxxxx",NeededFiles_Name = new string[] { "module1Conf.xml","module
编辑:看起来不可能像解决方案#2一样只有一个属性,所以我最终使用的解决方案#3不像解决方案#1那样容易出错.

我有一个属性如下:

// Solution #1 (working)
[Module(Name="Module1",Guid="xxxxx",NeededFiles_Name = new string[]
  {
    "module1Conf.xml","module1.sql","resourcesWindows","resourcesUnix",},NeededFiles_OS = new OSType[]
  {
    All,All,Windows,Unix,}
  NeededFiles_Component = new ComponentType[]
  {
    Server,Server,All
  }
)]

问题是填充NeededFile_Xxx属性并不容易.只有一个属性会更容易

// Solution #2 (NOT working)
[Module(Name="Module1",NeededFile = new FileInfo[]
  {
    new FileInfo("module1Conf.xml",Server),...
  }
)]

但是编译器不允许它(NeededFile不是有效的命名属性参数,因为它不是有效的属性参数类型.

我也可以将我的属性划分为几个并且可以

// Solution #3 (working)
[Module(Name="Module1",Guid="xxxxx"]
[NeededFile("module1Conf.xml",Server)]
[NeededFile("module1.sql",Server)]
[NeededFile(...)]

但我宁愿把一切都放在一边.

有可能吗?有没有更好的方法呢?

解决方法

为什么不允许(第二种选择)?我只是尝试了以下内容:

public class MyFileInfo
{
    public MyFileInfo(string fname,string somethingElse,string anotherThing);
}

public class ModuleAttribute : System.Attribute
{
    public ModuleAttribute(string Name,string Guid,params MyFileInfo[] myFileInfoList)
    {
    }
}

[Module("Module1","xxxx",new MyFileInfo("a","b","c"),"d","f"))
]
public class TestClass
{
}

并且编译器没有抱怨.我认为你几乎可以完成你想要做的事情.

编辑:这就是让我知道intellisense在半夜啤酒后半夜为我编译的结果.正如您(和我)发现的那样,Attribute参数必须是常量或常量列表 – 明确排除类和结构的限制.

我认为你能做的最好的事情就是将你试图标记的数据的序列化版本传递给属性.然后属性构造函数可以在运行时进行实际的对象初始化.这会丢失初始化程序的编译时检查,但会让您更接近您正在寻找的代码的紧凑性.

public class MyFileInfo
{
    string fname;
    string anotherThing;
    string somethingElse;
    public MyFileInfo(string serializedFileInfo)
    {
        string[] parts = serializedFileInfo.Split(',');
        fname = parts[0];
        anotherThing = parts[1];
        somethingElse = parts[2];
    }
    public static implicit operator MyFileInfo(string things)
    {
        return new MyFileInfo(things);
    }
}

public class ModuleAttribute : System.Attribute
{
    List<MyFileInfo> fiList;
    public ModuleAttribute(string Name,params string[] serializedFileInfoList)
    {
        fiList = serializedFileInfoList.Select(s => new MyFileInfo(s)).ToList();
    }
}

[Module("Module1","a,b,c","d,e,f"
    )
]
public class TestClass
{
}

实际上,我认为您应该通过每个文件的单独属性来处理它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读