Exemplo n.º 1
0
        /// <summary>
        /// Converts an <see cref="IMetadataReference"/> to a <see cref="MetadataReference"/> instance.
        /// </summary>
        /// <param name="metadataReference">The <see cref="IMetadataReference"/> to convert.</param>
        /// <param name="assemblyMetadataFactory">Factory invoked to get instances of <see cref="AssemblyMetadata"/>.</param>
        /// <returns>The converted <see cref="MetadataReference"/>.</returns>
        public static MetadataReference ConvertMetadataReference(
            this IMetadataReference metadataReference,
            Func <IMetadataFileReference, AssemblyMetadata> assemblyMetadataFactory)
        {
            var roslynReference = metadataReference as IRoslynMetadataReference;

            if (roslynReference != null)
            {
                return(roslynReference.MetadataReference);
            }

            var embeddedReference = metadataReference as IMetadataEmbeddedReference;

            if (embeddedReference != null)
            {
                return(MetadataReference.CreateFromImage(embeddedReference.Contents));
            }

            var fileMetadataReference = metadataReference as IMetadataFileReference;

            if (fileMetadataReference != null)
            {
                var metadata = assemblyMetadataFactory(fileMetadataReference);
                return(metadata.GetReference(filePath: fileMetadataReference.Path));
            }

            var projectReference = metadataReference as IMetadataProjectReference;

            if (projectReference != null)
            {
                using (var ms = new MemoryStream())
                {
                    projectReference.EmitReferenceAssembly(ms);

                    return(MetadataReference.CreateFromStream(ms, filePath: projectReference.ProjectPath));
                }
            }

            throw new NotSupportedException($"Unsupported type '{metadataReference.GetType()}'.");
        }