如何在Console App .NET 6.0的program.C中声明静态实例。
我创建了一个控制台应用程序.net 6.0
用于学习单例模式。 但是我已经观察到program.cs
文件的重大变化。
名称空间
,class
和main
方法已从program.cs
in .net 6.0 删除代码>。
我相信将在program.cs
中编写的代码将被视为main
方法中的代码。 但是我想创建两个使用全球式实例的静态方法,但我无法做到这一点。
通过声明下面的实例:
它给出了编译错误:
CS0106修饰符“静态”对此项目无效
它给出了编译错误:
cs8421:静态本地函数不能包含引用 'TableServers1'。
这是program.cs
的所有代码:
using SingletonApp;
static TableServers tableservers1 = TableServers.GetInstance();
static TableServers tableservers2 = TableServers.GetInstance();
Console.WriteLine("Hello, World!");
for (int i = 0; i < 5; i++)
{
Host1();
Host2();
}
Console.WriteLine();
static void Host1()
{
Console.WriteLine("Host1 Next server is: " + tableservers1.GetNextServer());
}
static void Host2()
{
Console.WriteLine("Host2 Next server is: " + tableservers2.GetNextServer());
}
请有人可以解释我们如何使用此新的Minified program.cs
,特别是使用全局实例和变量以及创建方法。
I have created a console application .NET 6.0
for learning of Singleton Pattern.
But I have observed a significant change in Program.cs
file.
namespace
, class
and Main
method have been removed from program.cs
in .NET 6.0
.
I believe the code that will be written in program.cs
will be considered as within Main
method.
But I want to create two static methods which are using globally intialized instances but I am not able to do that.
By declaring the instances like below:
It gives Compile Error:
CS0106 The modifier 'static' is not valid for this item
While using the instances in static methods like below:
It gives Compile Error:
CS8421: A static local function cannot contain a reference to
'tableservers1'.
Here is all the code of program.cs
:
using SingletonApp;
static TableServers tableservers1 = TableServers.GetInstance();
static TableServers tableservers2 = TableServers.GetInstance();
Console.WriteLine("Hello, World!");
for (int i = 0; i < 5; i++)
{
Host1();
Host2();
}
Console.WriteLine();
static void Host1()
{
Console.WriteLine("Host1 Next server is: " + tableservers1.GetNextServer());
}
static void Host2()
{
Console.WriteLine("Host2 Next server is: " + tableservers2.GetNextServer());
}
Please someone can explain how can we use this new minified program.cs
, specially to use global instance and variables and creating methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如此答案因为C#10您可以通过引入
公共部分类别comproge
(在位置)您的底部最高级别语句文件或在单独的文件中):但是我认为切换到“旧样式”
program
类或将静态字段移至另一类将是一个更好的选择。As in this answer since C# 10 you can achieve this by introducing
public partial class Program
(at the bottom of you top level statement file or in separate file):But I would argue that switching to "old style"
Program
class or moving static fields to another class would be a better option.