Created
May 2, 2023 08:59
-
-
Save 0x070696E65/ff64e0b29124af260bfcc9788f8626c4 to your computer and use it in GitHub Desktop.
C#リフレクションメモ2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var source = @" | |
using System; | |
using System.Text; | |
using System.Runtime; | |
using System.Linq; | |
public class Test1 | |
{ | |
public static string Message(string message) | |
{ | |
return message; | |
} | |
} | |
public class Test2 | |
{ | |
public static string Message(string message) | |
{ | |
return message; | |
} | |
} | |
"; | |
string assemblyName = Path.GetRandomFileName(); | |
var syntaxTree = CSharpSyntaxTree.ParseText(source); | |
var references = new MetadataReference[] | |
{ | |
MetadataReference.CreateFromFile(typeof(object).Assembly.Location), | |
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location), | |
MetadataReference.CreateFromFile(typeof(Console).Assembly.Location) | |
}; | |
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); | |
var compilation = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, references, compilationOptions); | |
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 test1Type = assembly.GetType("Test1"); | |
Type test2Type = assembly.GetType("Test2"); | |
MethodInfo messageMethod1 = test1Type.GetMethod("Message"); | |
MethodInfo messageMethod2 = test2Type.GetMethod("Message"); | |
var res1 = (string)messageMethod1.Invoke(null, new[] { "Hello from Test1!" }); | |
var res2 = (string)messageMethod1.Invoke(null, new[] { "Hello from Test2!" }); | |
Console.WriteLine(res1); | |
Console.WriteLine(res2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment