C#中Action委托的使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/371054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uses of Action delegate in C#
提问by Biswanath
I was working with the Action Delegates in C# in the hope of learning more about them and thinking where they might be useful.
我在 C# 中与 Action Delegates 一起工作,希望能更多地了解它们并思考它们可能有用的地方。
Has anybody used the Action Delegate, and if so why? or could you give some examples where it might be useful?
有没有人使用过 Action Delegate,如果有,为什么?或者你能举一些可能有用的例子吗?
采纳答案by arul
MSDN says:
MSDN 说:
This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.
Array.ForEach 方法和 List.ForEach 方法使用此委托对数组或列表的每个元素执行操作。
Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value.
除此之外,您可以将其用作通用委托,它接受 1-3 个参数而不返回任何值。
回答by Sorskoot
I used it as a callback in an event handler. When I raise the event, I pass in a method taking a string a parameter. This is what the raising of the event looks like:
我将它用作事件处理程序中的回调。当我引发事件时,我传入了一个将字符串作为参数的方法。这是事件引发的样子:
SpecialRequest(this,
new BalieEventArgs
{
Message = "A Message",
Action = UpdateMethod,
Data = someDataObject
});
The Method:
方法:
public void UpdateMethod(string SpecialCode){ }
The is the class declaration of the event Args:
是事件 Args 的类声明:
public class MyEventArgs : EventArgs
{
public string Message;
public object Data;
public Action<String> Action;
}
This way I can call the method passed from the event handler with a some parameter to update the data. I use this to request some information from the user.
这样我就可以使用一些参数调用从事件处理程序传递的方法来更新数据。我用它来请求用户的一些信息。
回答by Nathan W
I used the action delegate like this in a project once:
我曾经在一个项目中使用过这样的动作委托:
private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() {
{typeof(TextBox), c => ((TextBox)c).Clear()},
{typeof(CheckBox), c => ((CheckBox)c).Checked = false},
{typeof(ListBox), c => ((ListBox)c).Items.Clear()},
{typeof(RadioButton), c => ((RadioButton)c).Checked = false},
{typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
{typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
};
which all it does is store a action(method call) against a type of control so that you can clear all the controls on a form back to there defaults.
它所做的只是针对一种控件存储一个操作(方法调用),以便您可以将表单上的所有控件清除回那里的默认值。
回答by Programmin Tool
Well one thing you could do is if you have a switch:
那么你可以做的一件事是,如果你有一个开关:
switch(SomeEnum)
{
case SomeEnum.One:
DoThings(someUser);
break;
case SomeEnum.Two:
DoSomethingElse(someUser);
break;
}
And with the might power of actions you can turn that switch into a dictionary:
借助动作的强大力量,您可以将该开关转换为字典:
Dictionary<SomeEnum, Action<User>> methodList =
new Dictionary<SomeEnum, Action<User>>()
methodList.Add(SomeEnum.One, DoSomething);
methodList.Add(SomeEnum.Two, DoSomethingElse);
...
...
methodList[SomeEnum](someUser);
Or you could take this farther:
或者你可以更进一步:
SomeOtherMethod(Action<User> someMethodToUse, User someUser)
{
someMethodToUse(someUser);
}
....
....
var neededMethod = methodList[SomeEnum];
SomeOtherMethod(neededMethod, someUser);
Just a couple of examples. Of course the more obvious use would be Linq extension methods.
只是几个例子。当然,更明显的用途是 Linq 扩展方法。
回答by Binary Worrier
For an example of how Action<> is used.
有关如何使用 Action<> 的示例。
Console.WriteLine has a signature that satisifies Action<string>
.
Console.WriteLine 具有满足Action<string>
.
static void Main(string[] args)
{
string[] words = "This is as easy as it looks".Split(' ');
// Passing WriteLine as the action
Array.ForEach(words, Console.WriteLine);
}
Hope this helps
希望这可以帮助
回答by Aaron Powell
You can use actions for short event handlers:
您可以对短事件处理程序使用操作:
btnSubmit.Click += (sender, e) => MessageBox.Show("You clicked save!");
回答by Andrew Hare
Here is a small example that shows the usefulness of the Action delegate
这是一个小例子,展示了 Action 委托的用处
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Action<String> print = new Action<String>(Program.Print);
List<String> names = new List<String> { "andrew", "nicole" };
names.ForEach(print);
Console.Read();
}
static void Print(String s)
{
Console.WriteLine(s);
}
}
Notice that the foreach method iterates the collection of names and executes the print
method against each member of the collection. This a bit of a paradigm shift for us C# developers as we move towards a more functional style of programming. (For more info on the computer science behind it read this: http://en.wikipedia.org/wiki/Map_(higher-order_function).
请注意,foreach 方法迭代名称集合并print
针对集合的每个成员执行该方法。随着我们转向更具功能性的编程风格,这对我们 C# 开发人员来说是一种范式转变。(有关其背后的计算机科学的更多信息,请阅读:http: //en.wikipedia.org/wiki/Map_(higher-order_function)。
Now if you are using C# 3 you can slick this up a bit with a lambda expression like so:
现在,如果您使用的是 C# 3,您可以使用如下的 lambda 表达式稍微修饰一下:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String> { "andrew", "nicole" };
names.ForEach(s => Console.WriteLine(s));
Console.Read();
}
}
回答by Ron Skufca
I use it when I am dealing with Illegal Cross Thread Calls For example:
我在处理非法跨线程调用时使用它,例如:
DataRow dr = GetRow();
this.Invoke(new Action(() => {
txtFname.Text = dr["Fname"].ToString();
txtLname.Text = dr["Lname"].ToString();
txtMI.Text = dr["MI"].ToString();
txtSSN.Text = dr["SSN"].ToString();
txtSSN.ButtonsRight["OpenDialog"].Visible = true;
txtSSN.ButtonsRight["ListSSN"].Visible = true;
txtSSN.Focus();
}));
I must give credit to Reed Copsey SO user 65358 for the solution. My full question with answers is SO Question 2587930
我必须感谢 Reed Copsey SO 用户 65358 的解决方案。我的完整问题和答案是SO Question 2587930
回答by evilone
We use a lot of Action delegate functionality in tests. When we need to build some default object and later need to modify it. I made little example. To build default person (John Doe) object we use BuildPerson()
function. Later we add Jane Doe too, but we modify her birthdate and name and height.
我们在测试中使用了很多 Action 委托功能。当我们需要构建一些默认对象并且稍后需要修改它时。我做了一个小例子。为了构建默认的人(John Doe)对象,我们使用BuildPerson()
函数。后来我们也添加了 Jane Doe,但我们修改了她的出生日期、姓名和身高。
public class Program
{
public static void Main(string[] args)
{
var person1 = BuildPerson();
Console.WriteLine(person1.Firstname);
Console.WriteLine(person1.Lastname);
Console.WriteLine(person1.BirthDate);
Console.WriteLine(person1.Height);
var person2 = BuildPerson(p =>
{
p.Firstname = "Jane";
p.BirthDate = DateTime.Today;
p.Height = 1.76;
});
Console.WriteLine(person2.Firstname);
Console.WriteLine(person2.Lastname);
Console.WriteLine(person2.BirthDate);
Console.WriteLine(person2.Height);
Console.Read();
}
public static Person BuildPerson(Action<Person> overrideAction = null)
{
var person = new Person()
{
Firstname = "John",
Lastname = "Doe",
BirthDate = new DateTime(2012, 2, 2)
};
if (overrideAction != null)
overrideAction(person);
return person;
}
}
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime BirthDate { get; set; }
public double Height { get; set; }
}