C#—匿名方法和静态类使用

本文介绍了如何使用C#中的匿名方法实现数组元素求和,并展示了通过静态类及泛型方法进行数组元素查找的方法。

匿名方法

/* 
 * 编写一个使用匿名方法的委托,匿名方法实现计算整型数组个元素之和的功能。
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    delegate void MyDelegate(int[] a);
    class Program
    {
        static void Main(string[] args)
        {
            int[] b = { 2, 4, 6, 7, 8 };
            MyDelegate d= delegate(int []a)
            {
                int sum=0;
                for( int i=0;i<a.Length;i++)
                sum+=a[i];
                Console.WriteLine("和为:{0}",sum);
            };
            d(b);
            Console.ReadKey();
        }
    }
}

运行结果:

注意:

匿名方法将代码块作为参数来传递,在本应使用委托的任何地方,使用代码块来取代,将代码直接与委托实例相关联。


静态类

/* 
 * 创建静态方法,在其中定义一个泛型方法,实现查找数组元素的功能。
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    static class MyClass
    {
        public static int  Method<T>(int n,T b) where T :ArrayList
        {
            return (b.IndexOf(n)+1);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList b=new ArrayList();
            int []a={0,1,2,3,4,5,6,7,8,9,10};
            b.AddRange(a);
            int num=Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("该元素在第{0}个位置!",MyClass.Method<ArrayList>(num, b));
            Console.ReadKey();
        }
    }
}

运行结果:

注意:

静态类只包含静态成员;

静态类不可实例化,不可被继承。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值