1024programmer Asp.Net C# anonymous type RuntimeBinderException

C# anonymous type RuntimeBinderException

C# anonymous type RuntimeBinderException

Anonymous types are more convenient to use in some scenarios. For example, a certain type will only be used once, so defining a Class at this time does not make much sense. You can use anonymous types to solve the problem, but when using it across projects , you still need to pay attention to avoid RuntimeBinderException problems

Problem Description

For example, we have a class library project of type netstandard2.0, which has a method like this:

 public static class StandardClass
     {
         public static dynamic Get()
         {
             return new { prop1 = "hello", prop2 = 12 };
         }
     }
 

Then add the following example code to a net6.0 type console project

using ClassLibrary1;

 try
 {
     var test = StandardClass.Get();
     var prop1 = test.prop1;
 }
 catch (Exception e)
 {
     Console.WriteLine(e);
     throw;
 }
 

At this time, when we try to run this console project to obtain the prop1 value, at this time, a RuntimeBinderException

will be raised

Solution

Because anonymous types default to the access level of Internal. This means that there is no problem if you access this anonymous object through the Dynamic type in the same assembly, but if it crosses the assembly, RuntimeBinder will not be able to recognize this type, thus triggering the RuntimeBinderException exception. There are 2 ways to solve this problem:

  • Modify the return type to a strong type and cancel the anonymous type
  • Add the InternalsVisibleTo attribute to expose Internal level objects to the outside world (as shown in the figure below)

  • C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly
This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/c-anonymous-type-runtimebinderexception/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索