0

我一直在尝试使用源生成器并遇到一个奇怪的问题。

源代码生成器在对其代码进行更改后只会成功执行一次,但每次后续运行都会失败:

CSC : warning CS8032: An instance of analyzer Generator cannot be created from MyDir\CodeGeneration\bin\Debug\netstandard2.0\CodeGeneration.dll : Exception has been thrown by the target of an invocation..

我一一删除了部分代码并追踪到:

private Dictionary<string, Func<Table, object>> Properties { get; } = new();

这是一本我想通过反射填充以生成派生类的字典。如果我删除字典,问题就会消失。另外,如果我Table用其他东西代替。

不过没有什么特别的Table

    public class Table
    {
        public virtual int Object_ID { get; set; }
        public virtual int Schema_ID { get; set; }
        public virtual string Name { get; set; } = "";

        public Table()
        {
        }

        public Table(int object_ID, int schema_ID, string name)
        {
            Object_ID = object_ID;
            Schema_ID = schema_ID;
            Name = name;
        }
    }

我的猜测是从源生成器(在本例中为 .net 标准 2.0 类库)引用其他项目会导致问题?不能在源代码生成中使用反射似乎是一个很大的限制?

为了完整起见,我用来测试这个的生成器:

    [Generator]
    public class Generator : ISourceGenerator
    {
        private Dictionary<string, Func<Generator, object>> Properties { get; } = new();
        public void Execute(GeneratorExecutionContext context)
        {

        }

        public void Initialize(GeneratorInitializationContext context)
        {
#if DEBUG
            if (!Debugger.IsAttached)
            {
                Debugger.Launch();
            }
#endif
        }
    }
4

1 回答 1

0

canton7s 指向食谱的链接和关于包参考的建议实际上引导我找到了本次讨论中的解决方案。

Table在使用生成器的项目中,我需要更改对定义为 include的类库的现有引用OutputItemType="Analyzer"

ReferenceOutputAssembly="false"但在我的情况下不需要。

于 2022-02-28T14:37:40.113 回答