铸造委托Func键在C# [英] Cast delegate to Func in C#

查看:251
本文介绍了铸造委托Func键在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code:

 公共委托INT SomeDelegate(INT P);

公共静态INT公司(INT P){
    返回的p + 1;
}
 

我可以投公司 SomeDelegate Func键< INT,INT>

  SomeDelegate A =公司;
FUNC< INT,INT> B =公司;
 

但我不能投公司 SomeDelegate 和强制转换为 Func键℃后; INT,INT> 有这样的通常方式:

  Func键< INT,INT> C =(Func键< INT,INT>)一个; //Сompilation错误
 

我该怎么办呢?

解决方案

  SomeDelegate A =公司;
FUNC< INT,INT> B =公司;
 

是短期的。

  SomeDelegate A =新SomeDelegate(公司); //这里没有投
FUNC< INT,INT> B =新的函数功能:LT; INT,INT>(INC);
 

您无法施展SomeDelegate的实例函数求< INT,INT>出于同样的原因,你可以不投一个字符串字典< INT,INT> - 他们是不同类型的

本作品:

  Func键< INT,INT> C = X =>斧头);
 

这是语法糖

 类MyLambda
{
   SomeDelegate一个;
   公共美孚(SomeDelegate一){this.a =一个; }
   公众诠释调用(INT X){返回this.a(X); }
}

FUNC< INT,INT> C =新的函数功能:LT; INT,INT>(新MyLambda(一).Invoke);
 

I have code:

public delegate int SomeDelegate(int p);

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

I can cast Inc to SomeDelegate or Func<int, int>:

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

but I can't cast Inc to SomeDelegate and after that cast to Func<int, int> with usual way like this:

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

How I can do it?

解决方案

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

is short for

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

You can't cast an instance of SomeDelegate to a Func<int, int> for the same reason you can't cast a string to a Dictionary<int, int> -- they're different types.

This works:

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

which is syntactic sugar for

class MyLambda
{
   SomeDelegate a;
   public Foo(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);

这篇关于铸造委托Func键在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆