Я использую делегатов в течение многих лет, и на самом деле не особо задумывался о них
Но недавно я понял, что делегаты включили в подпись ссылку this
при ссылке на метод класса.
Приведенный ниже пример иллюстрирует пробел в моем понимании.
public class SomeClass
{
public SomeClass(int someProperty)
{
SomeProperty = someProperty;
}
public int SomeProperty
{
get;
set;
}
// Throw in a Member field into the mix
public int ClassAdd(int x, int y)
{
return x + y + SomeProperty;
}
}
public static class SomeStaticClass
{
public static int StaticAdd(int x, int y)
{
return x + y;
}
}
Почему я могу добавлять как статических, так и экземпляров подписчиков?
delegate int addDelegate(int x, int y);
class TestClass
{
delegate int addDelegate(int x, int y);
private void useDelegates()
{
addDelegate algorithm;
algorithm = SomeStaticClass.StaticAdd;
algorithm += new SomeClass(3).ClassAdd;
int answer = algorithm(5, 10);
}
}
Что на самом деле происходит ? ;)