标签: c# 委托详解
委托入门实例
复制代码
namespace ConsoleApplication1
{
public delegate void methodDelegate(string str);
class Program
{
static void Main(string[] args)
{
Student student = new Student();
Teacher teacher = new Teacher("王老师");
methodDelegate methodDelegate1 = new methodDelegate(student.getStudentName);
methodDelegate1 += teacher.getTeacherName; //可以指向不同类中的方法!
//methodDelegate1 += teacher.getClassName; 指向签名不符的方法时提示错误!
methodDelegate1.Invoke("张三");
Console.ReadLine();
}
}
class Student
{
private String name = "";
public Student (String _name)
{
this.name = _name ;
}
public Student() {}
public void getStudentName(String _name)
{
if (this.name != "" )
Console.WriteLine("Student's name is {0}", this.name);
else
Console.WriteLine("Student's name is {0}", _name);
}
}
class Teacher
{
private String name;
public Teacher(String _name)
{
this.name = _name;
}
public void getTeacherName(String _name)
{
if (this.name != "")
Console.WriteLine("Teacher's name is {0}", this.name);
else
Console.WriteLine("Teacher's name is {0}", _name);
}
public string getClassName()
{
return "Eanlish";
}
}
}
复制代码
上面代码中实现对委托的调用
最后将被调用的委托输出
3.委托的实现方式
第一种:常规实现
private delegate String getAString( string parament);
static void Main(String []args)
{
int temp = 40;
getAString stringMethod = new getAString(temp.ToString); //传递temp.ToString调用委托<br>
Console.WriteLine("String is {0}", stringMethod()); //stringMethod()调用已经接受参数的委托
Console.ReadLine();
}
第二种:多播委托
getAString stringMethod = new getAString(temp.ToString);
stringMethod += temp.ToString;
stringMethod -= temp.ToString;
这种调用之后,按照接受参数的次数, 委托会生成一个列表,每用+=调用一次,会增加一个列表项,-=调用一次,会移除一个列表项。
第三种:委托数组
当我们定义委托 让委托形成一个数组的时候,我们可以通过遍历数组的方式来调用它
复制代码
delegate double Operations(double x);
class Program
{
static void Main()
{
Operations[] operations =
{
MathOperations.MultiplyByTwo,
MathOperations.Square
};
for (int i = 0; i < operations.Length; i++)
{
Console.WriteLine("Using operations[{0}]:", i);
DisplayNumber(operations[i], 2.0);
DisplayNumber(operations[i], 7.94);
Console.ReadLine();
}
}
static void DisplayNumber(Operations action, double value)
{
double result = action(value);
Console.WriteLine(
"Input Value is {0}, result of operation is {1}", value, result);
}
}
struct MathOperations
{
public static double MultiplyByTwo(double value)
{
return value * 2;
}
public static double Square(double value)
{
return value * value;
}
}