【问题标题】:c# scripting Roslyn session not accepting referencec#脚本Roslyn会话不接受参考
【发布时间】:2020-07-07 17:35:17
【问题描述】:

我正在尝试在 c# .net 应用程序中执行一些任意的 c sharp 脚本,但我尝试了多种方法来添加程序集的外部文件引用,但它似乎从来没有工作抱怨我错过了程序集。代码如下:

        var globals = new Globals();
        globals.mventry = myCurrentmventry;
        ScriptState state = null;
        var scriptOptions = ScriptOptions.Default;

        //all the ways I have tried
        var metadata = MetadataReference.CreateFromFile(typeof(MVEntry).Assembly.Location);
        scriptOptions.AddReferences(metadata);     
        scriptOptions.AddReferences(@"\\path\to\Microsoft.MetadirectoryServicesEx.dll");
        scriptOptions.AddReferences(Assembly.GetAssembly(typeof(MVEntry)));       
        CSharpScript.RunAsync(@"string result;
                                if(mventry[""attribute""].Value ==""value"")
                                {result = ""yes"";}
                                else
                                {result = ""no"";}", scriptOptions)
                               .ContinueWith(s => state = s.Result).Wait();
        string result = state.Variables[0].Value.ToString();
        //Also tried this way for fun
        // string result CSharpScript.EvaluateAsync(@"mventry[""attribute""].Value", 
                                scriptOptions,globals);
    }

// 我的全局类

    public class Globals
    {
        public MVEntry mventry;
    }

无论我如何添加引用或尝试执行我得到的脚本:

Microsoft.CodeAnalysis.Scripting.CompilationErrorException: (1,1): 错误 CS0012:类型“MVEntry”是在不是 参考。您必须添加对程序集的引用 'Microsoft.MetadirectoryServicesEx,版本=4.1.4.0,文化=中性, PublicKeyToken=31bf3856ad364e35'

我可能在做一些明显错误的事情,但我只是看不到它,事实上,当我观看 scriptOptions 变量时,似乎没有任何元数据元素。任何帮助将不胜感激。

【问题讨论】:

    标签: c# roslyn csharpscript


    【解决方案1】:

    好的,事实证明,当您声明选项类型时,您需要在该点添加选项,它必须在声明后才能读取,否则我正在做一些根本错误的事情。无论如何,这对我有用:

    var scriptOptions = ScriptOptions.Default
                        .AddReferences(Assembly.GetAssembly(typeof(MVEntry)))
                        .AddImports(Microsoft.MetadirectoryServices);
    
    I added the directives also...it might help someone!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多