如何在C#中从lambda访问类成员?

时间:2018-05-05 22:14:24

标签: c#

在java中,我可以这样做

public class HelloWorld
{
  public static void main(String[] args)
  {
    OtherClass oc = new OtherClass();
    oc.a.run();
  }
}

public class OtherClass
{
  public int s = 3;
  public Runnable a = () -> System.out.println("s is " + s);
}

输出为s is 3。当我在C#中使用此代码尝试此操作时

using System;

namespace SomeNamespace
{
    public class Program
    {
        public static void Main(string[] args)
        {
            MyClass m = new MyClass();
            m.a.Invoke();
        }
    }

    public class MyClass
    {
        public int s = 3;
        public Action a = () => Console.WriteLine(s);
    }
}

然后我得到(23:51) A field initializer cannot reference the non-static field, method, or property 'SomeNamespace.MyClass.s'

0 个答案:

没有答案