c#中的代理delegate,怎么用?什么时候用?他对方法的密封性体现在什么地方?
一些简单的代理就是声明,然后实例化代理,然后调用,不能看出他的优势啊!和创建类的对象,然后调用方法有什么不同的,大家可以讨论一下。...
一些简单的代理就是声明,然后实例化代理,然后调用,不能看出他的优势啊!和创建类的对象,然后调用方法有什么不同的,大家可以讨论一下。
展开
1个回答
展开全部
using System;
namespace Ch06Ex05
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
delegate double processDelegate(double param1, double param2);
static double Multiply(double param1, double param2)
{
return param1 * param2;
}
static double Divide(double param1, double param2)
{
return param1 / param2;
}
static void Main(string[] args)
{
processDelegate process;
Console.WriteLine("Enter 2 numbers separated with a comma:");
string input = Console.ReadLine();
int commaPos = input.IndexOf(',');
double param1 = Convert.ToDouble(input.Substring(0, commaPos));
double param2 = Convert.ToDouble(input.Substring(commaPos + 1,
input.Length - commaPos - 1));
Console.WriteLine("Enter M to multiply or D to divide:");
input = Console.ReadLine();
if (input == "M")
process = new processDelegate(Multiply);
else
process = new processDelegate(Divide);
Console.WriteLine("Result: {0}", process(param1, param2));
}
}
}
namespace Ch06Ex05
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
delegate double processDelegate(double param1, double param2);
static double Multiply(double param1, double param2)
{
return param1 * param2;
}
static double Divide(double param1, double param2)
{
return param1 / param2;
}
static void Main(string[] args)
{
processDelegate process;
Console.WriteLine("Enter 2 numbers separated with a comma:");
string input = Console.ReadLine();
int commaPos = input.IndexOf(',');
double param1 = Convert.ToDouble(input.Substring(0, commaPos));
double param2 = Convert.ToDouble(input.Substring(commaPos + 1,
input.Length - commaPos - 1));
Console.WriteLine("Enter M to multiply or D to divide:");
input = Console.ReadLine();
if (input == "M")
process = new processDelegate(Multiply);
else
process = new processDelegate(Divide);
Console.WriteLine("Result: {0}", process(param1, param2));
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询