C# 从类定义函数(方法)

C# 从类定义函数(方法),c#,C#,我有以下代码: SendNotificationClass sendNotifiClass=新的SendNotificationClass(); 但我想从中定义一个名为“SendNotification”的函数 所以不是 SendNotificationClass sendNotifClass = new sendNotificationClass(); SendNotifClass.SendNotification(); 我想这样做: var sendNotif = new SendNot

我有以下代码:

SendNotificationClass sendNotifiClass=新的SendNotificationClass();
但我想从中定义一个名为“SendNotification”的函数

所以不是

SendNotificationClass sendNotifClass = new sendNotificationClass();
SendNotifClass.SendNotification();
我想这样做:

var sendNotif = new SendNotificationClass().SendNotification;
sendNotif(...)
如何定义?

您可以通过稍微更改语法来定义:

var sendNotif = () => (new sendNotificationClass()).SendNotification();
sendNotif()
如果
sendNotif
需要参数(如使用省略号所示),则只需将它们添加到代理定义中:

var sendNotif = (x, y, Z) => (new sendNotificationClass()).SendNotification(x, y, z);
sendNotif(a, b, c)

你有很多不同的选择。仅举几个例子:

无效发送通知()
public委托void NotifDelegate();
...
var sendNotifiClass=新的SendNotificationClass();
NotifDelegate sendNotif1=新的NotifDelegate(sendNotifClass.SendNotification);
NotifDelegate sendNotif2=sendNotifClass.SendNotification;
动作sendNotif3=委托{sendNotifClass.SendNotification();};
操作sendNotif4=()=>sendNotifClass.SendNotification();
动作sendNotif5=sendNotifClass.SendNotification;
用法

sendNotif1.Invoke()//任何一个
sendNotif1()//或
...
sendNotif5.Invoke()//任何一个
sendNotif5()//或
bool发送通知(字符串电子邮件)
公共委托bool NotifWithParamDelegate(字符串param1);
...
NotifWithParamDelegate notifWithParam1=新建NotifWithParamDelegate(sendNotifClass.SendNotification);
NotifWithParamDelegate notifWithParam2=sendNotifClass.SendNotification;
Func notifWithParam3=委托(字符串电子邮件){return sendNotifClass.SendNotification(电子邮件);};
Func notifWithParam4=电子邮件=>sendNotifClass.SendNotification(电子邮件);
Func notifWithParam5=sendNotifClass.SendNotification;
用法

bool issucess=notifWithParam1.Invoke(“a@b.c"); //任何一个
bool issucess=notifWithParam1(“a@b.c"); //或
...
bool issucess=notifWithParam5.Invoke(“a@b.c"); //任何一个
bool issucess=notifWithParam5(“a@b.c"); //或

在您的特定情况下(假设方法的返回类型是
void
),它将是
Action sendNotif=new sendNotificationClass().SendNotification。如果该方法具有返回类型(例如,
int
),则应使用
Func sendNotif=…
。创建具有与SenNotification方法匹配的签名的委托。然后调用它。