3

I'm trying to write a FxCop rule that matches classes that are adorned with the Serializable attribute, but it seems like the attribute is being ignored.

Eg. given this sample class

[Serializable]
[Description]
public class ClassWithSerializableMustHaveSerializableBaseClass : BaseClass
{
}

I would have thought this code from my custom rule would match successfully:

    public override ProblemCollection Check(TypeNode type)
    {
        if (type.Attributes.Any(a => a.Type.FullName == typeof(SerializableAttribute).FullName))
        {                
            var problem = new Problem(GetResolution(), type.SourceContext);

            Problems.Add(problem);
        }

        return Problems;
    }

But it isn't. If I change the matching type to the DescriptionAttribute, then it does work. Is there something magical about SerializableAttribute or have I missed something obvious?

4

2 回答 2

5

SerializableAttribute 有什么神奇之处吗

是的; 有许多属性实际上并未作为属性嵌入(即不是“自定义”部分)。一些反射 API 可以欺骗它,使它们看起来在那里,但不是所有的,也不是所有的时间(例如,这取决于程序集的加载方式)。

例子:

  • [Serializable]- 成为类型上的 IL 标志
  • [AssemblyVersion]- 成为装配标识的一部分
  • [AssemblyFileVersion]- 成为文件身份的一部分
于 2014-07-18T13:30:01.397 回答
4

事实证明 SerializableAttribute 是特殊的,相反,您需要检查 Flags 属性:

        if ((type.Flags & TypeFlags.Serializable) == TypeFlags.Serializable)
        {
            var problem = new Problem(GetResolution(type.BaseType.FullName, type.FullName), type.SourceContext);

            Problems.Add(problem);
        }
于 2014-07-18T13:17:54.487 回答