请帮助我使用 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
它可以工作,但我想保存它以保持代码干净。