委托使用

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Test
{
    
public class Test
    
{
        
//委托Delegate
        
//想象成C++中的函数指针,但是不同在于delegate完全面向对象——机封装方法有封装对象实例(历史)
        
//定义委托实际上是定义一个类型的委托,不是一个具体的实例
        
//委托类型指定它代表的方法的返回类型和参数表
        
//它代表具有相同参数列表和返回类型的任何方法
        public delegate double ProcessAnything(double d);
        
//创建委托实例——new关键字
        ProcessAnything pa = new ProcessAnything(account);
        
public static double account(double d)
        
{
            
return d;
        }

        
//括号里面是实例方法,此方法必须和代理声明的返回类型和参数列表相同
        
//委托的调用通过输入委托实例的名称和要传递给委托所表示的方法的参数
        public static double Compute(double t, ProcessAnything pa)
        
{
            
return pa(t);
        }

    }


    
//实例
    public class Student
    
{
        
public delegate string AdviseDelegate(int score);
        
public AdviseDelegate AdviseDelegateInstance;

        
public int score;
        
public void SetScore(int value)
        
{
            
if (value > 100 || value < 0)
            
{
                Console.WriteLine(
"Wrong");
            }

            
else
            
{
                score 
= value;
                
if (AdviseDelegateInstance != null)
                
{
                    
string result = AdviseDelegateInstance(score);
                    Console.Out.WriteLine(
"Result:" + result);
                }

            }

        }

    }


    
public class Teacher
    
{
        
public string Advise(int score)
        
{
            
if (score < 60)
            
{
                Console.WriteLine(score 
+ "Add Oil");
                
return "Not Pass";
            }

            
else
            
{
                Console.Out.WriteLine(score 
+ "Good not Perfect");
                
return "Pass!";
            }

        }

    }


    
class MainClass
    
{
        [STAThread]
        
static void Main(string[] args)
        
{
            Teacher teacher 
= new Teacher();
            Student student 
= new Student();
            student.AdviseDelegateInstance 
= new Student.AdviseDelegate(teacher.Advise);
            Console.WriteLine(
"Student got 49");
            student.SetScore(
49);
            Console.WriteLine(
"Student got 87");
            student.SetScore(
87);
            Console.ReadLine();
        }

    }

    
}
posted @ 2008-01-22 08:29  love .net FrameWork  阅读(497)  评论(0编辑  收藏  举报