在运行时访问DisplayClass对象上的属性

问题描述 投票:0回答:1

环境: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线。
  • Visual Studio debugger返回object id = …
  • this answer返回一个空的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的值?

c# dynamic reflection anonymous-function anonymous-types
1个回答
1
投票

编译器使用字段而不是属性生成闭包类型,因此IgnoresAccessChecksTo是一个字段。请改用as described here

© www.soinside.com 2019 - 2024. All rights reserved.