Skip to content

Instantly share code, notes, and snippets.

@0x070696E65
Last active May 2, 2023 13:14
Show Gist options
  • Save 0x070696E65/461888cfe5db4efa651c275edbd88f7f to your computer and use it in GitHub Desktop.
Save 0x070696E65/461888cfe5db4efa651c275edbd88f7f to your computer and use it in GitHub Desktop.
C#リフレクションメモ
var source = @"
using System;
using System.Collections.Generic;
public class MyRandom
{
public static Dictionary<string, int> GetRandomInt(int maxValue, string sig)
{
var random = new Random(sig.GetHashCode());
return new Dictionary<string, int>()
{
{sig, random.Next(maxValue + 1)}
};
}
}";
var options = CSharpParseOptions.Default
.WithLanguageVersion(LanguageVersion.CSharp8);
var syntaxTree = CSharpSyntaxTree.ParseText(source, options, "MyRandom.cs");
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
};
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(
"MyRandom.dll",
new[] { syntaxTree },
references,
compilationOptions);
using var stream = new MemoryStream();
var emitResult = compilation.Emit(stream);
if (emitResult.Success)
{
stream.Seek(0, SeekOrigin.Begin);
var assembly = AssemblyLoadContext.Default.LoadFromStream(stream);
var randomType = assembly.GetType("MyRandom");
//var method = randomType.GetMethod("GetRandomInt");
var method = randomType.GetMethod("GetRandomInt");
var result = (Dictionary<string, int>)(method.Invoke(null, new object[]{100, "AAA"}) ?? throw new InvalidOperationException());
Console.WriteLine($"Add(1, 5) = {result.Keys.FirstOrDefault()} : {result.Values.FirstOrDefault()}");
}
else
{
IEnumerable<Diagnostic> failures = emitResult.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment