简体   繁体   English

C#中的简单匿名方法

[英]Simple Anonymous Method in C#

See the second bit of code below.. code doesn't compile. 请参阅下面的第二部分代码。代码无法编译。 Am trying to figure out anon methods, and I get it.. 我正在尝试找出匿名方法,我明白了。

But not the example of not using anon methods which I found on the web, which doesn't compile 但不是使用我在网络上发现的无法编译的匿名方法的示例

Using VS2008.. compiling to .NET3.5 使用VS2008 ..编译为.NET3.5

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

namespace TestAnonymousMethods
{
    public class Program
    {
        // using an anon method
        static void Mainx(string[] args)
        {
            int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            int[] evenIntegers = Array.FindAll(_integers,
                                        // this is the anonymous method below
                                       delegate(int integer)
                                       {
                                           return (integer % 2 == 0);
                                       }
                );

            foreach (int integer in _integers) 
                Console.WriteLine(integer);

            foreach (int integer in evenIntegers)
                Console.WriteLine(integer);
        }

        // not using anon method
        static void Main(string[] args)
        {
            int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            int[] evenIntegers = Array.FindAll(_integers, IsEven); // **Compile error here**

            foreach (int integer in _integers)
                Console.WriteLine(integer);

            foreach (int integer in evenIntegers)
                Console.WriteLine(integer);
        }

        public bool IsEven(int integer)
        {
            return (integer % 2 == 0);
        }


    }
}
public static  bool IsEven(int integer)
{
    return (integer % 2 == 0);
}

Main is static so IsEven must be static too. Main是静态的,因此IsEven也必须是静态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM