Делегат броска в Func в C#

У меня есть код:

public delegate int SomeDelegate(int p);

public static int Inc(int p) {
    return p + 1;
}

Я могу бросить Inc к SomeDelegate или Func<int, int>:

SomeDelegate a = Inc;
Func<int, int> b = Inc;

но я не могу бросить Inc к SomeDelegate и после того броска к Func<int, int> с обычным путем как это:

Func<int, int> c = (Func<int, int>)a; // Сompilation error

Как я могу сделать это?

43
задан AndreyAkinshin 15 December 2009 в 11:22
поделиться

5 ответов

SomeDelegate a = Inc;
Func<int, int> b = Inc;

- это сокращение от

SomeDelegate a = new SomeDelegate(Inc); // no cast here
Func<int, int> b = new Func<int, int>(Inc);

. Вы не можете преобразовать экземпляр SomeDelegate в Func по той же причине вы не можете преобразовать строку в Dictionary - это разные типы.

Это работает:

Func<int, int> c = x => a(x);

что является синтаксическим сахаром для

class MyLambda
{
   SomeDelegate a;
   public MyLambda(SomeDelegate a) { this.a = a; }
   public int Invoke(int x) { return this.a(x); }
}

Func<int, int> c = new Func<int, int>(new MyLambda(a).Invoke);
48
ответ дан 26 November 2019 в 22:24
поделиться

Есть гораздо более простой способ сделать это, который упускают из виду все остальные ответы:

Func<int, int> c = a.Invoke; 

См. это сообщение в блоге для получения дополнительной информации.

67
ответ дан 26 November 2019 в 22:24
поделиться

Try this:

Func<int, int> c = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), 
                                                           b.Target,
                                                           b.Method);
29
ответ дан 26 November 2019 в 22:24
поделиться

Проблема в том, что:

SomeDelegate a = Inc;

На самом деле это не приведение. Это сокращенная форма:

SomeDelegate a = new SomeDelegate(Inc);

Следовательно, здесь нет актеров. Простым решением вашей проблемы может быть следующее (в C # 3.0)

Func<int,int> f = i=>a(i);
9
ответ дан 26 November 2019 в 22:24
поделиться

It is the same kind of problem as this:

public delegate int SomeDelegate1(int p);
public delegate int SomeDelegate2(int p);
...
  SomeDelegate1 a = new SomeDelegate1(Inc);
  SomeDelegate2 b = (SomeDelegate2)a;  // CS0030

which is the same kind of problem as:

public class A { int prop { get; set; } }
public class B { int prop { get; set; } }
...
  A obja = new A();
  B objb = (B)obja;  // CS0029

Objects cannot be casted from one type to an unrelated other type, even though the types are otherwise completely compatible. For lack of a better term: an object has type identity that it carries along at runtime. That identity cannot be changed after the object is created. The visible manifestation of this identity is Object.GetType().

4
ответ дан 26 November 2019 в 22:24
поделиться
Другие вопросы по тегам:

Похожие вопросы: