只要我在班级和班级ClassSameAssembly相同的班级中,下面的代码就能正常运行Program.但是当我将类移动ClassSameAssembly到一个单独的程序集时,RuntimeBinderException会抛出一个(见下文).有可能解决它吗?
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'object'不包含'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 …Run Code Online (Sandbox Code Playgroud) 在项目中考虑以下代码:
static void Main(string[] args)
{
DoSomething(new { Name = "Saeed" });
}
public static void DoSomething(dynamic parameters)
{
Console.WriteLine(parameters.Name);
}
Run Code Online (Sandbox Code Playgroud)
这就像一个魅力.但是,只要将这两个函数分成两个不同的项目,代码就会中断:
// This code is in a Console Application
static void Main(string[] args)
{
ExternalClass.DoSomething(new { Name = "Saeed" });
}
// However, this code is in a Class Library; Another project
public class ExternalClass
{
public static void DoSomething(dynamic parameters)
{
Console.WriteLine(parameters.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
我在第二种情况下得到的错误是:
object'不包含'Name'的定义(RuntimeBinderException)
为什么我会收到此错误?什么是替代方法?如何将动态参数传递给另一个库中的方法,并以简单的方式在那里使用它?
注意:我很熟悉,ExpandoObject我不想使用它.
在此示例控制台应用中:
class Program
{
static void Main()
{
DoAsyncFoo();
Console.ReadKey();
}
private static async void DoAsyncFoo()
{
var task = CollectStatsAsync();
dynamic foo = await task;
Console.WriteLine(foo.NumberOfCores);
}
private static async Task<dynamic> CollectStatsAsync()
{
return CollectStats();
}
private static dynamic CollectStats()
{
return new { NumberOfCores = 3 };
}
}
Run Code Online (Sandbox Code Playgroud)
当我把断点放到
Console.WriteLine(foo.NumberOfCores)
并在调试模式下评估foo.NumberOfCores,错误的输出是:
gatherStats.NumberOfCores'对象'不包含'NumberOfCores'的定义,并且没有扩展方法'NumberOfCores'接受类型'object'的第一个参数可以找到(你是否缺少using指令或汇编引用?)
因为gatherStats是"匿名对象",而不是"动态".但是,该函数返回动态,我将其指定为动态.
评估成功:
((dynamic)foo).NumberOfCores;
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我已经意识到如果我同步编写函数,调试器可以直接返回结果.所以它应该是异步的.
注意:我也尝试从函数返回Expando Object而不是Anonymous Type,结果是一样的.
c# asynchronous dynamic anonymous-methods visual-studio-2013