gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:52:46 31 4
gpt4 key购买 nike

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

  • 用户界面(Winform)
  • 存储(类库)
  • 业务层(类库)

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

业务层包含一个“ Controller ”类,它将驱动各层之间的交互。

Controller 类从 UI 中的 main() 启动。 Controller 依次从业务类启动一个实例

但是启动的对象在 Controller 类中不可用。认为我们做错了什么?

/* 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());
}
}

商业.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; }
}


}
}

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

}
}

Please find error here

最佳答案

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

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
}
}

Methods (C# Programming Guide)

A method is a code block that contains a series of statements. Aprogram causes the statements to be executed by calling the method andspecifying any required method arguments. In C#, every executedinstruction is performed in the context of a method. The Main methodis the entry point for every C# application and it is called by thecommon language runtime (CLR) when the program is started.

关于c# - 如何在分层模型中引用实例 - 当前上下文中不存在该名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53955834/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com