| name | tsinswreng-write-comment |
| description | 寫代碼一定要有註釋。寫代碼寫註釋時使用此skill |
代碼註釋規範
AI新寫代碼的時候即默認需要詳盡地添加註釋。 !應加盡加 寧濫勿缺!
添加註釋的位置
- 文件頭部
- 類型(class/interface/struct/enum等)
- 方法(不管是不是public)
- 類型的成員(包括字段和訪問器 事件等等、不管是不是public)
- 函數內部實現
目標
- 讓讀者快速理解「意圖、約束、邊界條件」等等,而不是重複代碼表面含義。
函數內部實現 加註釋的要求
- 應加盡加 寧濫勿缺 尤其是難一眼看懂的複雜邏輯 包括但不限于: 分支/狀態轉換
- 函數實現內 如果可以劃分出多個子步驟時、 在每個子步驟的開頭 添加概括性註釋。 如
DoSomething() {
......
}
禁止事項
- 不爲顯而易見的代碼添加機械式註釋。
- 修改代碼時禁止隨意刪除已有的註釋
示例
using System;
using System.Collections.Generic;
public class CacheManager {
private readonly Dictionary<string, (object Value, DateTime Expiry)> _cache = new();
public int Count => _cache.Count;
public void Set(string key, object value, DateTime absoluteExpiration) {
if (string.IsNullOrEmpty(key)){
throw new ArgumentNullException(nameof(key), "鍵不能爲空");
}
if (absoluteExpiration <= DateTime.UtcNow){
throw new ArgumentException("過期時間必須晚於當前時間", nameof(absoluteExpiration));
}
_cache[key] = (value, absoluteExpiration);
}
public bool TryGet(string key, out object? value) {
value = null;
if (!_cache.TryGetValue(key, out var entry))
return false;
if (entry.Expiry <= DateTime.UtcNow) {
_cache.Remove(key);
return false;
}
value = entry.Value;
return true;
}
}