小測驗,以下程式碼有什麼問題?(請忽略程式實用價值)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ClassLibrary
{
    /// <summary>
    /// 測試類別
    /// </summary>
    public class Boo
    {
        /// <summary>
        /// 數字
        /// </summary>
        public int Value { get; set; }
        /// <summary>
        /// 若 Value > 100,傳回true
        /// </summary>
        public bool IsBig
        {
            get
            {
                return Value > 100;
            }
        }
        /// <summary>
        /// 若 Value < 100,傳回true
        /// </summary>
        public bool IsSmall
        {
            get
            {
                return Value < 100;
            }
        }
        /// <summary>
        /// First Name & Last Name
        /// </summary>
        public string FullName { get; set; }
    }
}

答案藏在XML Documentation裡:註解用到特殊字元<、>及&卻未額外處理,轉成XML程式文件會爆炸:

「>」未與「<」成對時不易誤判,尚能正常顯示;但「<」及「&」會跟後方內容一起被解讀成HTML標籤或特殊符號,就會出現上圖中的<!—Badly formed XML comment ignored form member "…" –>。在專案使用DocsByReflection讀取XML文件,也跟著爆炸:(原本預期出現<member />的地方出現<!—... –>導致節點讀取失敗)

An unhandled exception of type 'System.InvalidCastException' occurred in DocsByReflection.dll
Additional information: Unable to cast object of type 'System.Xml.XmlComment' to type 'System.Xml.XmlElement'.

註解問題被視為警告不影響編譯,卻也常被忽略,直到轉為Help文件或用於整合時才發現。在要求「0 Warning」的專案裡註解問題很難被無視(如下),但你知道的,理想與現實總是有差距的… (掩面)

結論:當XML註解文字涉及<, >, &等Syntax Charactors,記得改用&lt; &gt;及&amp;。若出現XML Documentation相關錯誤,也請優先排除是否與特殊字元有關。

PS:在web.config/app.config中也要小心類似狀況


Comments

Be the first to post a comment

Post a comment