簡體   English   中英

在FxCop自定義規則中使用SerializationAttribute檢測類

[英]Detecting class with SerializationAttribute in a FxCop custom rule

我正在嘗試編寫一個FxCop規則,該規則匹配使用Serializable屬性裝飾的類,但似乎該屬性被忽略。

例如。 給出這個樣本類

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

我原以為我的自定義規則中的代碼會成功匹配:

    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;
    }

但事實並非如此。 如果我將匹配類型更改為DescriptionAttribute,那么它確實有效。 有關SerializableAttribute的神奇之處還是我錯過了一些明顯的東西?

是否有關於SerializableAttribute的神奇之處

是; 有許多屬性實際上並未作為屬性嵌入 (即不是“自定義”部分)。 一些反射API可以欺騙它,使它們看起來在那里,但不是全部,而不是所有的時間(例如,它取決於程序集的加載方式)。

例子:

  • [Serializable] - 成為該類型的IL標志
  • [AssemblyVersion] - 成為裝配標識的一部分
  • [AssemblyFileVersion] - 成為文件標識的一部分

事實證明SerializableAttribute是特殊的,而你需要檢查Flags屬性:

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

            Problems.Add(problem);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM