C# ‘dynamic’ cannot access properties from anonymo

2020-01-26 05:58发布

Code below is working well as long as I have class ClassSameAssembly in same assembly as class Program. But when I move class ClassSameAssembly to a separate assembly, a RuntimeBinderException (see below) is thrown. Is it possible to resolve it?

using System;

namespace ConsoleApplication2
{
    public static class ClassSameAssembly
    {
        public static dynamic GetValues()
        {
            return new
            {
                Name = "Michael", Age = 20
            };
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var d = ClassSameAssembly.GetValues();
            Console.WriteLine("{0} is {1} years old", d.Name, d.Age);
        }
    }
}

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Name'

at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at ConsoleApplication2.Program.Main(String[] args) in C:\temp\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 23

8条回答
疯言疯语
2楼-- · 2020-01-26 06:33

Below solution worked for me in my console application projects

Put this [assembly: InternalsVisibleTo("YourAssemblyName")] in \Properties\AssemblyInfo.cs of the separate project with function returning dynamic object.

"YourAssemblyName" is the assembly name of calling project. You can get that through Assembly.GetExecutingAssembly().FullName by executing it in calling project.

查看更多
混吃等死
3楼-- · 2020-01-26 06:34

A cleaner solution would be:

var d = ClassSameAssembly.GetValues().ToDynamic();

Which is now an ExpandoObject.

Remember to reference:

Microsoft.CSharp.dll
查看更多
登录 后发表回答