Здравствуйте, sergunok, Вы писали:
S>В чем разница между:
S>x.A += new Action(hndlr);
S>x.A += hndlr;
S>?
Смотря, что есть "hndlr". Скорее всего — никакой.
Здравствуйте, sergunok, Вы писали:
x.A += new Action(hndlr);
x.A += hndlr;
Если hndlr — метод, то никакой, 2я строчка — просто сокращённая форма записи.
Если hndlr — или экземпляр делегата, то:
Action a = () =>
{
};
Action b = new Action(a);
Action c = a;
Console.WriteLine("a == b? {0}", a == b);
Console.WriteLine("a == c? {0}", a == c);
Console.WriteLine("a == b.Target? {0}", a == b.Target as Action);
Console.WriteLine("a == c.Target? {0}", a == c.Target as Action);
Если hdlr — что-то ещё, то либо ошибки компиляции(разные
), либо ошибка в рантайме (если hdlr — dynamic).
Здравствуйте, Sinix, Вы писали:
S>Здравствуйте, sergunok, Вы писали:
S>S>x.A += new Action(hndlr);
S>x.A += hndlr;
S>
S>Если hndlr — метод, то никакой, 2я строчка — просто сокращённая форма записи.
S>Если hndlr — или экземпляр делегата, то:
S>S> Action a = () =>
S> {
S> };
S> Action b = new Action(a);
S> Action c = a;
S> Console.WriteLine("a == b? {0}", a == b);
S> Console.WriteLine("a == c? {0}", a == c);
S> Console.WriteLine("a == b.Target? {0}", a == b.Target as Action);
S> Console.WriteLine("a == c.Target? {0}", a == c.Target as Action);
S>
S>Если hdlr — что-то ещё, то либо ошибки компиляции(разные), либо ошибка в рантайме (если hdlr — dynamic).
А на при "x.A -= ..." нужно строго указывать то, что было в +=? или что ни указывай в -= hndlr, new Action(hndlr)- так или иначе уберет обработчик?
Здравствуйте, sergunok, Вы писали:
S>А на при "x.A -= ..." нужно строго указывать то, что было в +=? или что ни указывай в -= hndlr, new Action(hndlr)- так или иначе уберет обработчик?
Если hndlr — это метод, то не нужно.
Хинт:
Two delegates of the same type with the same targets, methods, and invocation lists are considered equal.
Important
In the .NET Framework version 1.0 and 1.1, two delegates were considered equal if their targets, methods, and invocation list were equal, even if the delegates were of different types.
static void A() { }
static void Main(string[] args)
{
Action a = A;
Action b = new Action(A);
Action c = a;
Action temp = A;
temp -= b;
Console.WriteLine("a == b? {0}", a == b);
Console.WriteLine("a == c? {0}", a == c);
Console.WriteLine("temp == null? {0}", temp == null);
Console.ReadKey();
}
Если используются разные делегаты — да.