当前位置: 首页>>代码示例>>C#>>正文


C# CodeAnalysis.MetadataReference类代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.MetadataReference的典型用法代码示例。如果您正苦于以下问题:C# MetadataReference类的具体用法?C# MetadataReference怎么用?C# MetadataReference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


MetadataReference类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了MetadataReference类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetAssembly

        /// <summary>
        /// Get assembly from the given text.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>Assembly</returns>
        protected Assembly GetAssembly(SyntaxTree tree)
        {
            Assembly assembly = null;
            
            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Machine).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(PSharpBugFindingRuntime).Assembly.Location)
            };

            var compilation = CSharpCompilation.Create(
                "PSharpTestAssembly", new[] { tree }, references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);
                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    assembly = Assembly.Load(ms.ToArray());
                }
            }

            return assembly;
        }
开发者ID:huangpf,项目名称:PSharp,代码行数:33,代码来源:BasePSharpTest.cs

示例2: Matches_IsTrue_WhenParametersAreEquivalent

        public void Matches_IsTrue_WhenParametersAreEquivalent()
        {
            var function1 = @"using System;
public static void Run(string id, out string output)
{
    output = string.Empty;
}";

            // Diferent formatting, qualified name, not using alias 
            var function2 = @"using System;
public static void Run( System.String id , 
out String output )
{
    string result = string.Empty;
    output = result;
}";

            var tree1 = CSharpSyntaxTree.ParseText(function1, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script));
            var tree2 = CSharpSyntaxTree.ParseText(function2, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script));

            var references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(string).Assembly.Location) };

            var compilation1 = CSharpCompilation.Create("test1", references: references).AddSyntaxTrees(tree1);
            var compilation2 = CSharpCompilation.Create("test2", references: references).AddSyntaxTrees(tree1);

            var signature1 = CSharpFunctionSignature.FromCompilation(compilation1, new FunctionEntryPointResolver());
            var signature2 = CSharpFunctionSignature.FromCompilation(compilation2, new FunctionEntryPointResolver());

            Assert.True(signature1.Equals(signature2));
            Assert.Equal(signature1.GetHashCode(), signature2.GetHashCode());
        }
开发者ID:isaacabraham,项目名称:azure-webjobs-sdk-script,代码行数:31,代码来源:CSharpFunctionSignatureTests.cs

示例3: Merge

        /// <summary>
        /// Adds aliases of a specified reference to the merged set of aliases.
        /// Consider the following special cases:
        /// 
        /// o {} + {} = {} 
        ///   If neither reference has any aliases then the result has no aliases.
        /// 
        /// o {A} + {} = {A, global}
        ///   {} + {A} = {A, global}
        ///   
        ///   If one and only one of the references has aliases we add the global alias since the 
        ///   referenced declarations should now be accessible both via existing aliases 
        ///   as well as unqualified.
        ///   
        /// o {A, A} + {A, B, B} = {A, A, B, B}
        ///   We preserve dups in each alias array, but avoid making more dups when merging.
        /// </summary>
        internal void Merge(MetadataReference reference)
        {
            if (reference.Properties.HasRecursiveAliases)
            {
                if (RecursiveAliasesOpt == null)
                {
                    RecursiveAliasesOpt = ArrayBuilder<string>.GetInstance();
                    RecursiveAliasesOpt.AddRange(reference.Properties.Aliases);
                    return;
                }
            }
            else
            {
                if (AliasesOpt == null)
                {
                    AliasesOpt = ArrayBuilder<string>.GetInstance();
                    AliasesOpt.AddRange(reference.Properties.Aliases);
                    return;
                }
            }

            Merge(
                aliases: reference.Properties.HasRecursiveAliases ? RecursiveAliasesOpt : AliasesOpt, 
                newAliases: reference.Properties.Aliases);
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:42,代码来源:MergedAliases.cs

示例4: TryGetReference

        internal static bool TryGetReference(
            Solution solution, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference)
        {
            // if we have one from snapshot cache, use it. it will make sure same compilation will get same metadata reference always.
            MetadataOnlyReferenceSet referenceSet;
            if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out referenceSet))
            {
                reference = referenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
                return true;
            }

            // okay, now use version based cache that can live multiple compilation as long as there is no semantic changes.

            // get one for the branch
            if (TryGetReferenceFromBranch(solution.BranchId, projectReference, finalOrDeclarationCompilation, version, out reference))
            {
                return true;
            }

            // see whether we can use primary branch one
            var primaryBranchId = solution.Workspace.PrimaryBranchId;
            if (solution.BranchId != primaryBranchId &&
                TryGetReferenceFromBranch(primaryBranchId, projectReference, finalOrDeclarationCompilation, version, out reference))
            {
                return true;
            }

            // noop, we don't have any
            reference = null;
            return false;
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:31,代码来源:MetadataOnlyReference.cs

示例5: Compile

        private static Assembly Compile(string razorGeneratedCode)
        {
            var razorSyntaxTree = CSharpSyntaxTree.ParseText(razorGeneratedCode);
            var assemblyName = Path.GetRandomFileName();
            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(Templater).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

            var compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { razorSyntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    var failures = result.Diagnostics.Where(IsError);
                    throw new InvalidOperationException();
                }

                ms.Seek(0, SeekOrigin.Begin);
                return Assembly.Load(ms.ToArray());
            }
        }
开发者ID:mmoore99,项目名称:RazorOnConsole,代码行数:31,代码来源:Templater.cs

示例6: GetAssemblyForConfiguration

        private static Assembly GetAssemblyForConfiguration(string fileContents)
        {
            var tmpl = @"
                using UrlFactory.Core;

                namespace DynamicUrlFactoryConfiguration
                {
                    public class ConfigFactory
                    {
                        public UrlRequestConfiguration GetConfiguration()
                        {
                            var config = new UrlRequestConfiguration();

                            {0}

                            return config;
                        }
                    }
                }";

            var syntaxTree = CSharpSyntaxTree.ParseText(String.Format(tmpl, fileContents));

            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof (object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof (UrlRequestConfiguration).Assembly.Location)
            };

            var compilation = CSharpCompilation.Create(
                Path.GetRandomFileName(),
                syntaxTrees: new[] {syntaxTree},
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);

                if (!result.Success)
                {
                    var failures = result.Diagnostics.Where(diagnostic =>
                        diagnostic.IsWarningAsError ||
                        diagnostic.Severity == DiagnosticSeverity.Error);

                    if (failures.Any())
                    {
                        throw new CompilationException("Could not compile config file");
                    }
                }

                // move to beginning of stream
                ms.Seek(0, SeekOrigin.Begin);

                var assembly = Assembly.Load(ms.ToArray());

                return assembly;
            }
        }
开发者ID:ryanlewis,项目名称:url-factory-proposal,代码行数:59,代码来源:ConfigurationObjectBuilder.cs

示例7: ResolveMissingAssembly

        public override PortableExecutableReference ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity)
        {
            ResolutionAttempts.Add(new ReferenceAndIdentity(definition, referenceIdentity));

            MetadataReference reference;
            string nameAndVersion = referenceIdentity.Name + (referenceIdentity.Version != AssemblyIdentity.NullVersion ? $", {referenceIdentity.Version}" : "");
            return _map.TryGetValue(nameAndVersion, out reference) ? (PortableExecutableReference)reference : null;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:8,代码来源:TestMissingMetadataReferenceResolver.cs

示例8: CreateForReference

        public IVsNavInfo CreateForReference(MetadataReference reference)
        {
            var portableExecutableReference = reference as PortableExecutableReference;
            if (portableExecutableReference != null)
            {
                return new NavInfo(this, libraryName: portableExecutableReference.FilePath);
            }

            return new NavInfo(this, libraryName: reference.Display);
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:10,代码来源:NavInfoFactory.cs

示例9: CompileHandlers

        public static IEnumerable<IMessageHandler> CompileHandlers(IEnumerable<string> paths)
        {
            var handlers = new List<IMessageHandler>();

            var assemblyName = "SkypeBot.Handlers";

            var syntaxTrees = paths
                .Select(path => File.ReadAllText(path))
                .Select(contents => CSharpSyntaxTree.ParseText(contents))
                .ToArray();

            var dotNetAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "mscorlib.dll")),
                MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.dll")),
                MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Core.dll")),
                MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Runtime.dll")),
                MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Xml.dll")),
                MetadataReference.CreateFromFile(Path.Combine(dotNetAssemblyPath, "System.Xml.Linq.dll")),
                MetadataReference.CreateFromFile(typeof(Program).Assembly.Location), // SkypeBot
                MetadataReference.CreateFromFile(typeof(ILogger).Assembly.Location), // Serilog
            };

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            var compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, references, options);

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);
                if (result.Success)
                {
                    var assembly = Assembly.Load(ms.ToArray());
                    foreach (var handlerType in assembly.GetTypes().Where(t => !t.IsInterface && typeof(IMessageHandler).IsAssignableFrom(t)))
                    {
                        handlers.Add((IMessageHandler)Activator.CreateInstance(handlerType));
                        Log.Information("Initializing handler {HandlerType}", handlerType.Name);
                    }
                }
                else
                {
                    foreach (var error in result.Diagnostics)
                    {
                        var message = error.GetMessage();
                        var span = error.Location.GetLineSpan();
                        Log.Error("{FileName} line {LineNumber}: {ErrorMessage:l}", span.Path, span.StartLinePosition.Line, message);
                    }
                }
            }

            return handlers;
        }
开发者ID:MatthewKing,项目名称:SkypeBot,代码行数:53,代码来源:MessageHandlerCompiler.cs

示例10: Compile

        private static CSharpCompilation Compile(string dllName, SyntaxTree[] allTrees, MetadataReference[] references)
        {
            var settings = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).
                WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
                .WithOptimizationLevel(OptimizationLevel.Release);

            CSharpCompilation compilation = CSharpCompilation.Create(
                dllName,
                allTrees,
                references,
                settings);

            return compilation;
        }
开发者ID:pzielinski86,项目名称:RuntimeTestCoverage,代码行数:14,代码来源:RoslynCompiler.cs

示例11: Compile

        public static void Compile(string source, string assemblyName)
        {
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                        diagnostic.IsWarningAsError ||
                        diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("{0} : {1}", diagnostic.Id, diagnostic.GetMessage());
                    }
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());

                    Type type = assembly.GetType("RoslynCompileSample.Writer");
                    object obj = Activator.CreateInstance(type);
                    Console.WriteLine("call compiled code :");
                    type.InvokeMember("Write",
                        BindingFlags.Default | BindingFlags.InvokeMethod,
                        null,
                        obj,
                        new object[] { "Hello World" });
                }
            }
        }
开发者ID:labeuze,项目名称:source,代码行数:47,代码来源:Compile_03.cs

示例12: ConvertText

 public static ConversionResult ConvertText(string text, MetadataReference[] references)
 {
     if (text == null)
         throw new ArgumentNullException(nameof(text));
     if (references == null)
         throw new ArgumentNullException(nameof(references));
     var tree = CS.SyntaxFactory.ParseSyntaxTree(SourceText.From(text));
     var compilation = CS.CSharpCompilation.Create("Conversion", new[] { tree }, references);
     try
     {
         return new ConversionResult(Convert((CS.CSharpSyntaxNode)tree.GetRoot(), compilation.GetSemanticModel(tree, true), null).NormalizeWhitespace().ToFullString());
     }
     catch (Exception ex)
     {
         return new ConversionResult(ex);
     }
 }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:17,代码来源:CSharpConverter.cs

示例13: ResolveMissingAssembly

        public override PortableExecutableReference ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity)
        {
            // resolve assemblies from the directory containing the test and from directory containing corlib

            string name = referenceIdentity.Name;
            string testDir = Path.GetDirectoryName(GetType().GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName);
            string testDependencyAssemblyPath = Path.Combine(testDir, name + ".dll");
            if (File.Exists(testDependencyAssemblyPath))
            {
                return MetadataReference.CreateFromFile(testDependencyAssemblyPath, s_resolvedMissingAssemblyReferenceProperties);
            }

            string fxDir = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName);
            string fxAssemblyPath = Path.Combine(fxDir, name + ".dll");
            if (File.Exists(fxAssemblyPath))
            {
                return MetadataReference.CreateFromFile(fxAssemblyPath, s_resolvedMissingAssemblyReferenceProperties);
            }

            return null;
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:21,代码来源:TestRuntimeMetadataReferenceResolver.cs

示例14: CreateCompilation

        public static Compilation CreateCompilation(MetadataReference metadataReference, string language = LanguageNames.CSharp)
        {
            var references = new[]
            {
                metadataReference
            };

            Compilation compilation = null;
            if (language == LanguageNames.CSharp)
            {
                compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(
                    "Temp", references: references);
            }
            else
            {
                compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create(
                    "Temp", references: references);
            }

            return compilation;
        }
开发者ID:rgmills,项目名称:SourceBrowser,代码行数:21,代码来源:MetadataReading.cs

示例15: GetReferenceNavInfo

        internal IVsNavInfo GetReferenceNavInfo(MetadataReference reference)
        {
            var portableExcutableReference = reference as PortableExecutableReference;
            if (portableExcutableReference != null)
            {
                return new NavInfo(
                    this.LibraryGuid,
                    this.SymbolToolLanguage,
                    libraryName: portableExcutableReference.FilePath);
            }

            var compilationReference = reference as CompilationReference;
            if (compilationReference != null)
            {
                return new NavInfo(
                    this.LibraryGuid,
                    this.SymbolToolLanguage,
                    libraryName: compilationReference.Display);
            }

            return null;
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:22,代码来源:AbstractObjectBrowserLibraryManager_NavInfo.cs


注:本文中的Microsoft.CodeAnalysis.MetadataReference类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。