是否可以在不知道名字的情况下调用方法?我想这是一个存储为变量的方法,如下所示:
public static Method Example;
private static void DoSomething()
{
//Something
}
private static void Main()
{
Example = DoSomething();
}
public static void ExecuteSomething()
{
Example();
}
有类似的东西,还是类似的功能?我看过代表们,我不确定我是否正确理解它们,或者它是否是我正在寻找的。 p>
答案 0 :(得分:2)
您所描述的内容称为Action // A void function
Action<T> // A void function that accepts a parameter of type T
Action<Tin1, Tin2, ...> // A void function that accepts Tx parameters
Func<T> // A function that returns an object of type T
Func<Tout, Tin1, Tin2, ...> // A function that returns Tout an accepts Tx as parameters
Predicate<T> // A function that returns bool and accepts parameter T
。它们可用于变量/ field / property / eventhandler声明。 C#附带了一些方便的泛型,可用于描述您期望的功能。一些例子:
delegate
或者,如果您想使用delegate void MySpecialEventHandler(object sender, object data)
关键字编写自己的代理:
//EventHandler definition
public delegate void PrintedSomethingEventHandler(string message);
//Event
public event PrintedSomethingEventHandler PrintedSomething;
//e.g. "Function Hook"
private Func<string,string> _externalFilter;
public void SetFilter(Func<string,string> filter)
{
_externalFilter = filter;
}
private void PrintA(string message)
{
Debug.WriteLine(message);
}
private void PrintB(string message)
{
Console.WriteLine(message);
}
private bool ContainsProfanity(string message)
{
return message.Contains("%$&!");
}
public void Print(string message, bool debug)
{
Action<string> action;
Predicate<string> filter = ContainsProfanity;
if(filter(message))
return;
if(_externalFilter != null)
message = _externalFilter(message);
if(debug)
action = PrintA;
else
action = PrintB;
action(message);
if(PrintedSomethingEventHandler != null)
PrintedSomethingEventHandler(message);
}
示例:
{{1}}