Last active
August 6, 2022 19:28
-
-
Save Charles-YYH/97785d39b72bef2df1b639a5e0081289 to your computer and use it in GitHub Desktop.
Delegate.Create Delegate 示例
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
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