簡體   English   中英

為什么連接調試器時,即時編譯的C#代碼不起作用?

[英]Why does C# code compiled on the fly not work when a debugger is attached?

我有以下C#項目,目標是.NET 4.0,它接受源代碼文件,動態地將其編譯成一個程序集,然后執行該程序集中包含的類型的靜態方法。

這可以按預期工作,只要我沒有附加調試器啟動程序。 在這種情況下,我在調用xmlSerializer.Serialize(sw, family);遇到異常xmlSerializer.Serialize(sw, family); 更確切地說, System.InvalidOperationException內的System.TypeInitializationException內的System.NullReferenceException

如果我采用相同的程序,在項目中包含源代碼文件並將其直接編譯到主程序集中,無論是否附加調試器,我都不會得到異常。

請注意,我的項目引用了與動態編譯時列出的完全相同的程序集。

無論調試器是否附加,為什么動態編譯的代碼都很重要? 我錯過了什么?

主文件Program.cs

using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Linq;

namespace DebugSerializeCompiler
{
    class Program
    {
        static void Main()
        {
            if (!Environment.GetCommandLineArgs().Contains("Compile"))
            {
                DebugSerializeCompiler.SerializerTest.Run();
            }
            else
            {
                Assembly assembly;
                if (TryCompile("..\\..\\SerializerTest.cs", new[]{ "Microsoft.CSharp.dll",
                   "System.dll", "System.Core.dll", "System.Data.dll", "System.Xml.dll" }, 
                   out assembly))
                {
                    Type type = assembly.GetType("DebugSerializeCompiler.SerializerTest");
                    MethodInfo methodInfo = type.GetMethod("Run");
                    methodInfo.Invoke(null, null);
                }
            }
            Console.ReadKey();
        }

        static bool TryCompile(string fileName, string[] referencedAssemblies, 
           out Assembly assembly)
        {
            bool result;

            CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
            var compilerparams = new CompilerParameters 
                                     {
                                        GenerateExecutable = false, 
                                        GenerateInMemory = true
                                     };
            foreach (var referencedAssembly in referencedAssemblies)
            {
                compilerparams.ReferencedAssemblies.Add(referencedAssembly);
            }

            using (var reader = new StreamReader(fileName))
            {
                CompilerResults compilerResults = 
                   compiler.CompileAssemblyFromSource(compilerparams, reader.ReadToEnd());
                assembly = compilerResults.CompiledAssembly;
                result = !compilerResults.Errors.HasErrors;
                if (!result)
                {
                    Console.Out.WriteLine("Compiler Errors:");
                    foreach (CompilerError error in compilerResults.Errors)
                    {
                        Console.Out.WriteLine("Position {0}.{1}: {2}", 
                           error.Line, error.Column, error.ErrorText);
                    }
                }
            }

            return result;
        }
    }
}

文件編譯成單獨的程序集SerializerTest.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace DebugSerializeCompiler
{
    public  class SerializerTest
    {
        public static void Run()
        {
            Console.WriteLine("Executing Run()");
            var family = new Family();
            var xmlSerializer = new XmlSerializer(typeof(Family));

            TextWriter sw = new StringWriter();
            try
            {
                if (sw == null) Console.WriteLine("sw == null");
                if (family == null) Console.WriteLine("family == null");
                if (xmlSerializer == null) Console.WriteLine("xmlSerializer == null");
                xmlSerializer.Serialize(sw, family);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught:");
                Console.WriteLine(e);
            }
            Console.WriteLine(sw);
        }
    }

    [Serializable]
    public class Family
    {
        public string LastName { get; set; }

        public List<FamilyMember> FamilyMembers { get; set; }
    }

    [Serializable]
    public class FamilyMember
    {
        public string FirstName { get; set; }
    }
}

這是用於在Windows 7上使用Visual C#2010 Express編譯項目的csproj文件:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>8.0.30703</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{7B8D2187-4C58-4310-AC69-9F87107C25AA}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>DebugSerializeCompiler</RootNamespace>
    <AssemblyName>DebugSerializeCompiler</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <TargetFrameworkProfile>Client</TargetFrameworkProfile>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="SerializerTest.cs">
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

它對我來說很好。

但是,如果我不得不猜測你發生了什么,那就是因為你正在用你的主項目編譯類並動態編譯它,序列化器會對使用哪個程序集而失敗感到困惑。 您可以嘗試將事件附加到AppDomain.CurrentDomain.AssemblyResolve並查看是否有任何程序集無法在那里解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM