【发布时间】:2018-01-11 17:55:40
【问题描述】:
玩弄 C# 7 的本地函数后,我发现了一些有趣的行为。考虑以下程序:
public void Main()
{
Console.WriteLine("Entered Main");
DoSomething("");
}
private void DoSomething(object obj)
{
Console.WriteLine("Entered DoSomething");
Generic((dynamic)obj);
GenericLocal(obj);
GenericLocal((dynamic)obj); // This breaks the program
void GenericLocal<T>(T val) => Console.WriteLine("GenericLocal");
}
private void Generic<T>(T val) => Console.WriteLine("Generic");
这会产生:
进入主界面
...然后抛出BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)。堆栈跟踪:
at UserQuery.DoSomething(Object obj)
at UserQuery.Main()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
(我在 LINQPad 中运行它,但我从 dotnetfiddle 得到了类似的结果。)
删除代码中指示的行会产生您期望的输出:
进入主界面
进入 DoSomething
通用
通用本地
谁能解释一下原因?
【问题讨论】:
标签: c# generics dynamic c#-7.0