2012-04-30 96 views
2

我已经创建了属于MEF的自定义属性,我希望定义与该类相关的id列表,以便我可以查询它们。将列表添加到系统属性

而且该类必须包含在自身定义,这是很重要的,这就是为什么我想过使用:

[SignalSystemData("ServiceIds", new List<int>(){1})] 

我应如何处理?

我的搜索的实现如下:

 var c = new Class1(); 
     var v = c.EditorSystemList; 

     foreach (var lazy in v.Where(x=>x.Metadata.LongName=="ServiceIds")) 
     { 
      if (lazy.Metadata.ServiceId.Contains(serviceIdToCall)) 
      { 
       var v2 = lazy.Value; 
       // v2 is the instance of MyEditorSystem 
       Console.WriteLine(serviceIdToCall.ToString() + " found"); 

      }else 
      { 
       Console.WriteLine(serviceIdToCall.ToString() + " not found"); 
      } 
     } 

我与定义导出类应该是这样的:

[Export(typeof(IEditorSystem))] 
[SignalSystemData("ServiceIds", new List<int>{1})] 
public class MyEditorSystem1 : IEditorSystem 
{ 
    void test() 
    { 
     Console.WriteLine("ServiceID : 1"); 
    } 
} 


public interface IEditorSystem 
{ 
} 

[MetadataAttribute] 
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] 
public class SignalSystemDataAttribute : ExportAttribute 
{ 
    public SignalSystemDataAttribute(string longName, List<int> serviceId) 
     : base(typeof (IEditorSystem)) 
    { 
     LongName = longName; 
     ServiceId = serviceId; 
    } 

    public string LongName { get; set; } 
    public List<int> ServiceId { get; set; } 

} 

public interface IEditorSystemMetadata 
{ 
    string LongName { get; } 
    List<int> ServiceId { get; } 
} 
+0

这不会飞。 [属性值必须是(编译时)常量。](http://msdn.microsoft.com/en-us/library/yd21828z.aspx) –

+0

@ Christian.K这就是我所知道的,所以我试图找到方式会怎样,而不是诉诸于使用昏迷分离的字符串。 – cpoDesign

+0

啊,对不起。你可能想在你的问题中指出这一点。我的答案也是如此。 –

回答

0

要解决的编译时间常数问题,您有以下选择:

  • 使用特殊格式的字符串(即逗号分隔的整数列表,因为您已经s uggested)。
  • 使用多个重载,每个重载的ID都有不同数量的参数。如果你有太多的ID需要传递,这会变得混乱。
  • 使用params int[] ids作为构造函数的最后一个参数。这将起作用,但不符合CLS - 如果这对您很重要。
  • 最容易使用数组int []的说法。

当然你也可以使用上述的组合。有一些重载说与1至5 ID参数,并提供一个字符串参数或params int[]参数为那些(希望)的角落情况下,超载参数是不够的。

更新:刚刚发现this问题/答案。可能不是重复,但处理相同的问题(主要)。

+0

thnx这是我一直在寻找。 – cpoDesign