Skip to content

Instantly share code, notes, and snippets.

@Charles-YYH
Last active August 6, 2022 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Charles-YYH/97785d39b72bef2df1b639a5e0081289 to your computer and use it in GitHub Desktop.
Save Charles-YYH/97785d39b72bef2df1b639a5e0081289 to your computer and use it in GitHub Desktop.
Delegate.Create Delegate 示例
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Playground;
internal static class Program
{
private static void Main()
{
Processor.Process(12); // ==> Process int
Processor.Process("string"); // ==> Process string
Processor.Process(1.0); // ==> Process double
}
}
[AttributeUsage(AttributeTargets.Method)]
internal class ProcessorAttribute : Attribute
{
public readonly Type Type;
public ProcessorAttribute(Type type)
{
Type = type;
}
}
internal static class Processor
{
public static Dictionary<Type, Action<object>> Dict { get; private set; } = null!;
[ModuleInitializer]
public static void Init()
{
Dict = typeof(Processor).GetMethods(BindingFlags.Static | BindingFlags.Public)
.SelectMany(methodInfo =>
{
if (methodInfo.GetCustomAttribute<ProcessorAttribute>() is not { } attribute)
return Enumerable.Empty<(Type type, Action<object> action)>();
var action = (Action<object>) Delegate.CreateDelegate(typeof(Action<object>), null, methodInfo);
return new[] { (attribute.Type, action) };
})
.ToDictionary(tuple => tuple.type, tuple => tuple.action);
}
public static void Process(object o)
{
Dict[o.GetType()].Invoke(o);
}
[Processor(typeof(int))]
public static void ProcessInt(object value)
{
Debug.Assert(value is int);
Console.Out.WriteLine("Process int");
}
[Processor(typeof(double))]
public static void ProcessDouble(object value)
{
Debug.Assert(value is double);
Console.Out.WriteLine("Process double");
}
[Processor(typeof(string))]
public static void ProcessString(object value)
{
Debug.Assert(value is string);
Console.Out.WriteLine("Process string");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment