https://dotnetfiddle.net/446j0U链接以进行复制(在.net 4.7.2上失败,不在.net核心上)
public class TEST {
static public void Main(string[] args)
{
var test = new { Text = "test", Slab = "slab"};
Console.WriteLine(test.Text); //outputs test
Console.WriteLine(TEST.TestMethod(test)); //outputs slab
}
static public string TestMethod(dynamic obj)
{
return obj.Slab;
}
}
Run Code Online (Sandbox Code Playgroud)
在同一个函数中访问匿名对象工作正常,但是当我尝试在函数中传递它时,出现异常
运行时异常(第14行):尝试通过方法'DynamicClass.CallSite.Target(System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,System.Object)'访问类型'<> f__AnonymousType0`2'失败了
堆栈跟踪:
[System.TypeAccessException:尝试通过方法'DynamicClass.CallSite.Target(System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,System.Object)'访问类型'<> f__AnonymousType0`2'失败。]位于System.Dynamic.UpdateDelegates.UpdateAndExecute1 [T0,TRet](CallSite网站,T0 arg0)的TEST.TestMethod(Object obj)处的CallSite.Target(Closure,CallSite,Object):TEST.Main(String [] args处的第14行):第9行
通过@RandRandom编辑:
由于悬赏期已近,我决定编辑此问题。
到目前为止,给定的答案都无法真正回答眼前的问题,只能给出避免错误的方法。
OP清楚地(在评论中)表示他知道解决方法,并且当前正在使用解决方法。
这些问题仍然存在
到目前为止,这里是OP的信息: