环境::VS2017,针对.NET Core 2.1的C#7.0。
我正在尝试编写一个伪/模拟类用于单元测试,并且在访问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
将id
投射到Guid
会抛出NullReferenceException
,即使Visual Studio调试器显示tgt
对象具有id
属性:
评论:
object id = …
行。tgt.GetType()
返回MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepository.<>c__DisplayClass8_0
tgt.GetType().GetProperties()
返回一个空的PropertyInfo
数组。[assembly: InternalsVisibleTo("MyCompany.Application.Web.Test")]
和MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepository
类都添加了MyCompany.Application.Web.Controllers
属性,据我所知,这是唯一涉及的两个类呼叫链。没什么区别。IgnoresAccessChecksTo
as described here闲逛,但无法进行任何编译。如何获取id
的值?
答案 0 :(得分:1)
编译器使用字段而不是属性生成闭包类型,因此a-.@foo--a
是一个字段。请改用id
。