環境: VS2017,針對 .NET Core 2.1 的 C# 7.0。我正在嘗試編寫一個用于單元測試的假/模擬類,并且我在訪問DisplayClass對象上的屬性時遇到了困難,我知道這是來自匿名函數的閉包類。我的代碼如下所示:namespace MyCompany.Application.Web.Test.Fakes{ public class FakeElasticClient : IElasticClient { public FakeElasticClient() { } public Task<ISearchResponse<T>> SearchAsync<T>(Func<SearchDescriptor<T>, ISearchRequest> selector = null, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var methodName = selector.Method.Name; dynamic tgt = selector.Target; object id = tgt?.GetType().GetProperty("id")?.GetValue(tgt, null); int? total; if (methodName.Contains("Quux")) { total = CountSomething((Guid)id); } else { total = CountSomethingElse((Guid)id); } return Task.Run(() => new FakeSearchResponse<T>(total ?? 0) as ISearchResponse<T>); } // … below here follows a couple thousand other methods即使 Visual Studio 調試器顯示該對象具有一個屬性,強制轉換id為也會Guid拋出一個:NullReferenceExceptiontgtid注釋:我從這個答案object id = …中偷了線。tgt.GetType()返回MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepository.<>c__DisplayClass8_0tgt.GetType().GetProperties()返回一個空PropertyInfo數組。受這篇博文的啟發,我為 the和class添加了一個[assembly: InternalsVisibleTo("MyCompany.Application.Web.Test")]屬性,據我所知,這是調用鏈中唯一涉及的兩個類。沒有任何區別。MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepositoryMyCompany.Application.Web.Controllers我嘗試IgnoresAccessChecksTo 按照此處描述的方法進行操作,但無法編譯任何內容。如何檢索 的值id?
- 1 回答
- 0 關注
- 87 瀏覽
添加回答
舉報
0/150
提交
取消