首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >发现StructLayoutAttribute StyleCop

发现StructLayoutAttribute StyleCop
EN

Stack Overflow用户
提问于 2014-04-16 07:03:14
回答 1查看 96关注 0票数 0

我正在尝试编写一个StyleCop规则,它检查可维护性约定。

当以结构为目标时,如果结构是用StructLayoutAttribute声明的,我想跳过它。

正如下面的代码所描述的,我的目标是一个结构。如果结构包含StructLayoutAttribute,我想返回。

但是,我如何将该属性放入包含方法中,因为它没有包含在StyleCop API中。

编辑:我为我尝试过的内容添加了新的逻辑;使用下面所有的尝试方法,带有属性的struct中的字段仍然会被StyleCop标记。

代码语言:javascript
复制
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);
            }
        }

    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-16 08:47:24

我自己设法到了那里,虽然有点脏,但它做得很好。如果有人知道如何真正瞄准属性,请告诉我!

它所做的就是我使用了一个bool,如果struct-属性包含文本"StructLayout“,它将设置为true。

然后,在下面我检查属性是否为false,如果属性为false,则如果字段不是只读的,则添加违规。

代码语言:javascript
复制
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);
                }
            }
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23102281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档