我正在使用 NDepend,在下面的代码中,它检测到这种代码异味。但是如果我添加只读,那么它就不会编译。namespace todo{ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; public static class DocumentDBRepository<T> where T : class { private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"]; private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"]; private static DocumentClient client; public static async Task<T> GetItemAsync(string id) { try { Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id)); return (T)(dynamic)document; } catch (DocumentClientException e) { if (e.StatusCode == System.Net.HttpStatusCode.NotFound) { return null; } else { throw; } } }警告线是:private static DocumentClient client;您建议如何修复此 NDepend 警告?规则说明:此规则警告未声明为只读的静态字段。在面向对象编程中,保存可修改状态的自然工件是实例字段。这种可变的静态字段会在运行时造成对预期状态的混淆,并损害代码的可测试性,因为每个测试都会重复使用相同的可变状态。关于该主题的更多讨论可以在这里找到:http : //codebetter.com/patricksmacchia/2011/05/04/back-to-basics-usage-of-static-members/
1 回答
萧十郎
TA贡献1815条经验 获得超13个赞
尝试将初始化移动到声明:
private static readonly DocumentClient client = new DocumentClient( . . . . );
- 1 回答
- 0 关注
- 157 浏览
添加回答
举报
0/150
提交
取消