【问题标题】:How correctly create class from message如何从消息中正确创建类
【发布时间】:2020-11-18 07:37:28
【问题描述】:

如何正确地从其他具有结构的类中创建类:

message ResultDto {
    bool Result = 1;
    repeated string Errors = 2;
    ResultModuleDto Module = 3;
}

来自

message ResultModuleDto {
   string Name = 1;
   string Path = 2;
   repeated SectionCollectionDto SectionCollection = 3;
}

message SectionCollectionDto {
    string Name = 1;
    string Path = 2;
    repeated HelpFileDto Files = 3;
}

message HelpFileDto {
    string Name = 1;
    string Path = 2;
}

我尝试像类var module = new ResultModuleDto { Name = moduleDto.Name, Path = moduleDto.Path };一样创建

但我发现了 System.Memory 异常。

【问题讨论】:

  • 显示的原型没有什么异常;您能否提供完整的异常消息和理想的堆栈跟踪?这应该工作正常。另外:您使用什么工具从原型中获取 C# 模型? (至少有 2 个我能想到,所以:这很重要)。更好的是一个可运行的示例来显示您在此处所做的事情 - 再次,显示的架构非常好且正常,因此它对上下文没有帮助。
  • 消息:测试方法 Help.Servers.Tests.UnitTest1.StudyRepositoryService_A3s 引发异常:System.TypeInitializationException:“ResultDto”类型的初始化程序引发异常。 ---> System.IO.FileLoadException:无法加载文件或程序集“System.Memory,版本 = 4.0.1.0,文化 = 中性,PublicKeyToken = cc7b13ffcd2ddd51”或其依赖项之一。发现程序集清单定义与程序集引用不匹配。 (来自 HRESULT 的异常:0x80131040)。
  • 堆栈跟踪:FieldCodec.ForString (UInt32 tag, String defaultValue) FieldCodec.ForString (UInt32 tag) line 56 ResultDto.cctor () line 101 --- 内部异常堆栈跟踪结束 --- ResultDto.ctor()HelpServiceGrpc.GetAllModules(ModuleDto moduleDto, ServerCallContext context) line 32 d__0.MoveNext() line 25 --- 从上一个位置结束的堆栈跟踪
  • 抛出异常---TaskAwaiter.ThrowForNonSuccess(任务任务)TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)ThreadOperations.ExecuteWithAbortSafety(动作动作)

标签: c# grpc


【解决方案1】:

从扩展消息信息来看,听起来您正在使用 .NET Framework 4.something;好消息是:这不是一个大问题,尽管我确实强烈建议尽可能使用 .NET Core 3.1 或 .NET 5。然后问题就消失了,而且您将使用一个非常更好的平台。

您看到的是缺少必要的“程序集绑定重定向”的结果,这是由于一些非常复杂的内部 .NET Framework 打包细节,以及工具中的一个已知错误,这意味着构建不会自动生成所需的程序集绑定重定向(它的意思是,它只是:一个错误)。

这意味着您需要在您的应用程序(即可执行文件或网络应用程序)中手动添加绑定重定向。 这里有更多详细信息https://nickcraver.com/blog/2020/02/11/binding-redirects/ - 但最终只是意味着调整您的 app.config/web.config 文件以包含与帖子中的示例非常相似的部分 - 在这种情况下System.Runtime.CompilerServices.Unsafe,但同样的概念也适用于System.Memory(另一个“已知罪犯”),即

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0"/>
      </dependentAssembly>
      <!-- ...and maybe some more... -->
    </assemblyBinding>
  </runtime>
</configuration>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
相关资源
最近更新 更多