Delegates internals

本文通过实例代码详细解析了C#中委托的两种调用方式及其内部实现原理,并探讨了Lambda表达式的内部处理机制。揭示了编译器如何将简单的委托调用转换为Invoke方法调用,以及Lambda表达式如何被编译成特定类。

I was just digging inside the delegates, action and anonymous delegates via lambda expression. I started to ask a few curious questions to myself and thus set out to dig inside to answer them. While doing so, I found a few interesting things which I would like to share with you all. Hope it is useful:

First I wrote a sample code as shown below:

Action del = () => Console.WriteLine(“Hello”);
del();
del.Invoke();

Well yes, the code is very simple, but I started to wonder and asked a question myself, what is the difference between the above two different styles of delegate invocation.

If in case you’re not aware of it, every delegate internally is represented as a class type having just four important methods: BeginInvokeInvokeEndInvoke, and Ctor. There is nothing much to explain about these methods.

I looked inside the IL and came to know that the above two styles of delegate invocation is in fact the same. The compiler just converts del() to del.Invoke(). So there will be twodel.Invoke() statements as shown in the below IL opcodes:

IL_0022: callvirt instance void [mscorlib]System.Action::Invoke()
IL_0027: nop
IL_0028: ldloc.0
IL_0029: callvirt instance void [mscorlib]System.Action::Invoke()

Next I asked myself how lambda expressions used above are treated internally. I found out that the lambda expression which I was using in the code is treated as a class internally in the IL. The below code produced two classes for the anonymous delegates I used:

MyDelegate del = () => (2 + 2).ToString();
del = () => (4 + 4).ToString();\

Let's look into the IL and see what charm the compiler has done:

// Fields
.field private static class ConsoleApplication.Program/MyDelegate ‘CS$<>9__CachedAnonymousMethodDelegate2′
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
.field private static class ConsoleApplication.Program/MyDelegate ‘CS$<>9__CachedAnonymousMethodDelegate3′
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)

As you can see, it has produced two classes for each of those anonymous delegates with the name shown above. No matter where the anonymous delegates are declared, they do get the same naming styles. But I still wonder and look for an answer why all anonymous delegates are prefixed with CS$<>9__. May be Microsoft chose to keep it that way? No idea! If you know, kindly leave a comment.

That’s all I could find so far, I shall surely share more if I find out more :)

Thanks

### C# Delegates vs Python Function Pointers and Callable Objects In the context of programming languages like C# and Python, both offer mechanisms to pass functions as arguments or store them in variables. However, these two languages implement this concept differently. #### C# Delegates A delegate in C# is a type that represents references to methods with a particular parameter list and return type[^1]. The primary use case for delegates includes event handling within .NET applications but extends far beyond just events. A simple example demonstrates how one can define and invoke a delegate: ```csharp // Define a delegate that takes no parameters and returns void. public delegate void SimpleDelegate(); class Program { static void Main() { // Instantiate the delegate with a method reference. SimpleDelegate myDelegate = new SimpleDelegate(SayHello); // Invoke the delegate. myDelegate(); } public static void SayHello() { Console.WriteLine("Hello from Delegate!"); } } ``` Delegates are strongly typed which means they enforce compile-time checking on signatures ensuring only compatible methods get assigned to them. #### Python Function Pointers and Callable Objects Unlike C#, where delegates provide strong typing over function pointers, Python uses dynamic typing allowing any object implementing `__call__` protocol to be treated as callable. This flexibility enables not only regular functions but also classes defining custom behavior through special methods such as `__call__`. Here's an illustration using plain functions alongside class-based callables: ```python def greet(name="World"): """Simple greeting function.""" print(f"Hello {name}!") class Greeter: def __init__(self, message): self.message = message def __call__(self, name="Everyone"): """Callable instance method""" print(f"{self.message}, {name}") greet() greeter_instance = Greeter("Good morning") greeter_instance() # Assigning either directly works due to duck-typing nature of Python. callable_objects = [greet, greeter_instance] for obj in callable_objects: obj() ``` This approach provides greater flexibility at runtime since there isn't strict enforcement regarding argument count/types until actual invocation occurs. #### Comparison Summary While both approaches allow passing around executable code blocks, key differences lie in their design philosophies: - **Type Safety**: C#'s delegate system enforces stricter rules about what kinds of methods may be referenced by each delegate signature versus Python’s more permissive model relying heavily upon conventions rather than compiler checks. - **Syntax Complexity**: Defining and working with delegates requires explicit syntax elements (`delegate`, instantiation), whereas Python leverages its general-purpose calling mechanism without requiring additional keywords specific solely to callbacks. - **Use Cases**: Although originally intended primarily for GUI frameworks and asynchronous operations, modern usage spans across various domains including functional reactive programming patterns; meanwhile, Python treats all first-class citizens equally making it suitable even outside traditional callback scenarios. --related questions-- 1. How does lambda expression support differ between C# and Python? 2. What advantages do anonymous inner classes have over delegates when used inside Java compared to C#? 3. Can you explain multicast delegates in C#? Are similar constructs available in Python? 4. In terms of performance characteristics, how do C# delegates compare against Python's built-in types supporting the callable interface? 5. Explore advanced features provided by C# language related specifically towards enhancing delegate functionality.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值