来自字符串的 Roslyn 脚本通过 Microsoft.CodeAnalysis.CSharp.Scripting 与内部扩展不起作用

问题描述

请帮助我使用 Microsoft.CodeAnalysis.CSharp.Scripting。我想调用内部扩展方法,但不起作用。

我有 3 个项目。 首先是模型:

namespace Models
{
    public class Foo
    {
        public int A { get; set; } = 5;
    }
}

在第二个中,我创建了一个带有公共扩展方法internal这很重要!)静态类:

namespace Store.Decorators
{
    internal static class FooDecorator
    {
        public static int Ext(this Foo foo)
            => foo.A;
    }
}

以及带有 roslyn 脚本的装饰器,用于从外部使用它:

namespace Store
{
    public static class DecoratorProvider
    {
        private static readonly Lazy<Func<Foo,int>> decorator
            = new Lazy<Func<Foo,int>>(() => CreateAsync().Result);

        private static readonly ScriptOptions options
            = ScriptOptions.Default
                           .AddReferences(Assembly.Load("Store"))
                           .AddImports("Store.Decorators");

        private static readonly string includeAllDecorator = "x => x.Ext()";

        private static async Task<Func<Foo,int>> CreateAsync()
            => await csharpscript.EvaluateAsync<Func<Foo,int>>(includeAllDecorator,options);

        public static Func<Foo,int> IncludeAll()
            => decorator.Value;
    }
}

并使用第三个项目中的最后一个

public sealed class DecoratorUser
    {
        public int A(Foo foo)
            => DecoratorProvider.IncludeAll()(foo);
    }

但它失败了:

System.AggregateException: "(1,8): error CS1061:" Foo "does not contain a deFinition for" Ext ",and Could not find an available extension method" Ext "taking type" Foo "as the first argument (possibly missing a using directive or assembly link). "

我尝试在 Store.csproj(带有内部装饰器的第二个项目)中添加 InternalVisibleto,但它没有帮助:

  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleto">
      <_Parameter1>Microsoft.CodeAnalysis.CSharp.Scripting</_Parameter1>
  </AssemblyAttribute>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleto">
      <_Parameter1>Microsoft.CodeAnalysis.Scripting</_Parameter1>
  </AssemblyAttribute>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleto">
        <_Parameter1>Microsoft.CodeAnalysis</_Parameter1>
  </AssemblyAttribute>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleto">
        <_Parameter1>Microsoft</_Parameter1>
  </AssemblyAttribute>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleto">
        <_Parameter1>Domain</_Parameter1>
  </AssemblyAttribute>

没有 internal 它也能工作,但我想保存它以保持代码干净。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)