C# 操作的成功/失败项说明
本文关键字:失败 说明 成功 操作 | 更新日期: 2023-09-27 18:36:44
我在Windows Phone 7 C#示例中找到了下面的方法。 在其中,您可以看到方法中使用的术语成功和失败。 我尝试使用任一术语"转到定义",Visual Studio没有跳转到任一术语的定义。 我尝试使用术语"操作","成功","失败","C#"和"参数"搜索Google,但没有找到任何有用的内容。 在这种情况下,成功和失败是宏还是类似的东西? 我在哪里可以获得有关它们的作用以及如何使用它们的解释? 请注意,将鼠标悬停在失败上时,工具提示帮助会显示"参数操作<字符串>失败字符串>"。
public void SendAsync(string userName, string message, Action success, Action<string> failure)
{
if (socket.Connected) {
var formattedMessage = string.Format("{0};{1};{2};{3};{4}",
SocketCommands.TEXT, this.DeviceNameAndId, userName, message, DateTime.Now);
var buffer = Encoding.UTF8.GetBytes(formattedMessage);
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = this.IPEndPoint;
args.SetBuffer(buffer, 0, buffer.Length);
args.Completed += (__, e) => {
Deployment.Current.Dispatcher.BeginInvoke(() => {
if (e.SocketError != SocketError.Success) {
failure("Your message can't be sent.");
}
else {
success();
}
});
};
socket.SendAsync(args);
}
}
它们是用作"回调函数"的委托。基本上,它们是提供给可以在该函数内部调用的另一个函数的函数。也许较小的样本更有意义:
static void PerformCheck(bool logic, Action ifTrue, Action ifFalse)
{
if (logic)
ifTrue(); // if logic is true, call the ifTrue delegate
else
ifFalse(); // if logic is false, call the ifFalse delegate
}
在下面的示例中打印 False,因为1 == 2
计算结果为 false。因此,logic
在PerformCheck
方法中是错误的。因此,它调用ifFalse
委托。如您所见,ifFalse
打印到控制台:
PerformCheck(1 == 2,
ifTrue: () => Console.WriteLine("Yep, its true"),
ifFalse: () => Console.WriteLine("Nope. False."));
而这个将打印为true..1 == 1
因为计算结果为true。所以它称之为ifTrue
:
PerformCheck(1 == 1,
ifTrue: () => Console.WriteLine("Yep, its true"),
ifFalse: () => Console.WriteLine("Nope. False."));
将Action
(也Func
)视为保存其他方法的变量。
你可以向Action
传递、赋值和基本上做任何其他变量的任何操作,但你也可以像方法一样调用它。
假设您的代码中有两种方法:
public void Main(){
Action doWork;
doWork = WorkMethod;
doWork();
}
private void WorkMethod(){
//do something here
}
您可以将工作方法分配给操作,就像对变量进行任何赋值一样。然后,您可以调用 doWork,就好像它是一个方法一样。它在这个例子中不是特别有用,但你可能会看到标准变量的所有好处是如何应用的。
您以几乎相同的方式使用Action
和Func
。唯一真正的区别是Action
表示void
,而Func
需要返回类型。
您还可以使用泛型。例如,Action<int>
用签名表示方法
void methodName(int arg){}
Action<int, string>
会
void methodName(int arg1, string arg2){}
Func
相似,Func<int>
是:
int methodName(){}
Func<string, int>
将是:
int methodName(string arg){}
记住,Func
定义中的最后一个类型是返回类型,即使它首先出现在实际方法签名中。