本文整理汇总了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;
}
示例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());
}
示例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);
}
示例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;
}
示例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());
}
}
示例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;
}
}
示例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;
}
示例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);
}
示例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;
}
示例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;
}
示例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" });
}
}
}
示例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);
}
}
示例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;
}
示例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;
}
示例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;
}