环境:VS2017,C#7.0,面向.NET Core 2.1。
我正在尝试编写一个假/模拟类用于单元测试,而我在访问DisplayClass
对象上的属性时遇到困难,我理解这是a closure class from an anonymous function。
我的代码看起来像这样:
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
属性,但是将qazxsw poi投射到qazxsw poi会抛出一个qazxsw poi。
NullReferenceException
评论:
tgt
偷走了id
线。object id = …
tgt.GetType()
数组。MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepository.<>c__DisplayClass8_0
的启发,我在tgt.GetType().GetProperties()
和PropertyInfo
类中添加了一个this blog post属性,据我所知,这是调用链中唯一涉及的两个类。没有任何区别。[assembly: InternalsVisibleTo("MyCompany.Application.Web.Test")]
MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepository
,但无法编译任何东西。如何检索MyCompany.Application.Web.Controllers
的值?
编译器使用字段而不是属性生成闭包类型,因此IgnoresAccessChecksTo
是一个字段。请改用as described here。