如何在分层模型中引用实例 - 该名称在当前上下文中不存在

Maa*_*els 2 c#

我正在开发3层解决方案:

  • UI(Winform)
  • 存储(类库)
  • 业务层(类库)

UI引用业务,业务引用存储.

业务层包含一个类"控制器",它将驱动层之间的交互.

控制器类从UI中的main()启动.控制器轮流从业务类启动实例

但是,启动的对象在控制器类中不可用.我们做错了什么?

/* UI: Program.cs */ 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Business;

namespace UI
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Business.Controller instController = new Business.Controller(); 

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new UI());
        }
    }
Run Code Online (Sandbox Code Playgroud)

Business.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Storage;

namespace Business
{
    public class Business
    {

        private int myVar;

        public int MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

Controller.CS

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

namespace Business
{
    public class Controller
    {
        Business instBusiness = new Business();

        /* line below fails, the instBusiness is not recognized) */

        instBusiness

    }
}
Run Code Online (Sandbox Code Playgroud)

请在这里找到错误

AAA*_*ddd 7

你不能在没有方法的情况下在类中执行任意代码,

public class Controller
{

    // Fields, properties, methods and events go here...

    // note, this only works because its initializing a field 
    // its the same as initializing in a constructor
    Business instBusiness = new Business();

    // nope, not going to work
    // instBusiness

    public Controller()
    { 
       // yay!
       instBusiness.MyProperty = 5
    }

    public void SomeOtherMethod()
    { 
       // yayer!
       instBusiness.MyProperty = 5
    }
}
Run Code Online (Sandbox Code Playgroud)

方法(C#编程指南)

方法是包含一系列语句的代码块.程序通过调用方法并指定任何必需的方法参数来执行语句.在C#中,每个执行的指令都在方法的上下文中执行.Main方法是每个C#应用程序的入口点,它在程序启动时由公共语言运行库(CLR)调用.