2014-04-16 18 views
0

我想寫一個StyleCop規則檢查可維護性約定。發現StructLayoutAttribute StyleCop

當定位一個Struct時,如果用一個StructLayoutAttribute聲明,我想跳過Struct。

如以下代碼所述,我定位了一個Struct。如果Struct包含StructLayoutAttribute,我想返回。

但是,如何將屬性放在contains方法中;因爲它不包含在StyleCop API中?

編輯:我添加了我嘗試過的新邏輯;在下面嘗試的所有方法中,具有該屬性的結構中的字段仍然會被StyleCop標記。

public void IsStructNameCorrect(Struct structItem) 
{ 
    string attribText = ""; 

    if (structItem.Attributes.Count == 1) 
     return; 

    if(structItem.Attributes.Contains(/*StructLayoutAttributeHere*/) 
     return; 

    foreach (Attribute attrib in structItem.Attributes) 
    { 
     attribText = attribText + attrib.CodePartType; 
    } 

    if (attribText.Contains("Layout")) 
     return; 

    foreach (CsElement csElement in structItem.ChildElements) 
    { 
     if (csElement.ElementType == ElementType.Field) 
     { 
      Field field = (Field)csElement; 
      if (!field.Readonly) 
      { 
       AddViolation(field, field.LineNumber, "FieldNotReadOnly", field.Name); 
      } 
     } 

    } 
} 

回答

0

我設法到那裏呢;儘管這種方式很骯髒,但它確實有效。如果任何人知道如何實際定位屬性,請告訴我!

它做了什麼是我用一個布爾如果結構屬性包含文本「StructLayout」設置爲true。

然後下面我檢查屬性是否爲false,如果是我添加違規如果該字段不只是只讀。

public void IsStructNameCorrect(Struct structItem) 
{ 
    string attribText = ""; 
    bool hasStructLayout = false; 

    foreach (Attribute attrib in structItem.Attributes) 
     attribText = attribText + attrib.Text; 

    if (attribText.Contains("StructLayout")) 
     hasStructLayout = true; 

    if (!hasStructLayout) 
    { 
     foreach (CsElement csElement in structItem.ChildElements) 
     { 
      if (csElement.ElementType == ElementType.Field) 
      { 
       Field field = (Field)csElement; 
       if (!field.Readonly) 
       { 
        AddViolation(field, field.LineNumber, "FieldNotReadOnly", field.Name); 
       } 
      } 
     } 
    } 
}