介绍
使用
普通委托详解
static void Main(string[] args)
{
int x = 100;
int y = 300;
//Get the pointer of the function "ToStirng" and apply it to the varible getAString
GetAString getAString = new GetAString(x.ToString);
GetAString getAString2 = x.ToString;//2nd Way to define: same as above
Console.WriteLine(getAString());//Usable while calling by varible "getAString"
Console.WriteLine(getAString2());//Usable while calling by varible "getAString2"
string str = getAString.Invoke();//2nd way to call
string str2 = getAString2.Invoke();//2nd way to call
Console.WriteLine(str);
Console.WriteLine(str2);
MethodHolder myMethod = new MethodHolder(y.ToString);
Console.WriteLine(AnotherMethod(myMethod));
}
//Signature of the delegate
delegate void VoidFuncWithOneParameter(int parameter);
delegate int IntFuncWithOneParameter(int parameter);
delegate int IntFuncWithTwoParameters(int parameterInt, string parameterStr);
delegate string GetAString();//This will be treated as a class
/*!IMPORTANT!*/
delegate string MethodHolder();
//delegate can be used to send a method as parameter to another method
static string AnotherMethod(MethodHolder method)
{
return method();//just like a callback-function in JS
}
Action委托详解
static void Main(string[] args)
{
//Action is a delegate which points to a void method without parameters
Action voidMethod = Method;
voidMethod();
//Action<type of parameter> can points to a void method with parameters
Action<int> voidMethodWithParameters = MethodWithParameters;
voidMethodWithParameters(5);
}
static void Method()
{
Console.WriteLine("This is a method which returns nothing.");
}
static void MethodWithParameters(int parameter)
{
if (parameter > 0)
{
for (int i = 0; i < parameter; i++)
{
Console.WriteLine("This is a void method with a parameter.");
}
}
else
{
Console.WriteLine("Parameter should be greater than 0");
}
}
Func委托详解
与Action委托不同的是,Func委托可以代理具有返回值的方法。
static void Main(string[] args)
{
//The last parameter in "Func" is the type of return-value the method
//while the former parameters are all the parameters' type of the target method
Func<string, int, bool, float> matureMethod = MatureMethod;
matureMethod("Hello world!", 6, true);
//The single parameter means the return-value of the method
Func<bool> simpleMethod = SimpleMethod;
Console.WriteLine(simpleMethod());
}
static float MatureMethod(string parameterStr, int parameterInt, bool parameterBool)
{
if (parameterBool && parameterInt > 0)
{
for (int i = 0; i < parameterInt; i++)
{
Console.WriteLine($"{i} : {parameterStr}");
}
return 0.618f;
}
else
{
Console.WriteLine("3rd parameter is set to false or the 2nd parameter is smaller than 0");
return 3.14f;
}
}
static bool SimpleMethod()
{
return true;
}
多播委托
作者:艾孜尔江;转载或使用请标明出处。