C# 如何在c中创建全局对象?

C# 如何在c中创建全局对象?,c#,.net,global-variables,C#,.net,Global Variables,我想使我定义的类的对象成为全局对象,但我得到了一个错误。 我在做这样的事情: namespace HotelSystem { public static class GlobalVariables { public static login_log cashier = new login_log(); public static List<customer> customer = new List<customer>();

我想使我定义的类的对象成为全局对象,但我得到了一个错误。 我在做这样的事情:

namespace HotelSystem
{
    public static class GlobalVariables
    {
        public static login_log cashier = new login_log();
        public static List<customer> customer = new List<customer>();
    }
}
我得到了这个错误:

Inconsistent accessibility: field type 'HotelSystem.Helpers.login_log' is less accessible than field 'HotelSystem.GlobalVariables.cashier'

Inconsistent accessibility: field type 'System.Collections.Generic.List<HotelSystem.Helpers.customer>' is less accessible than field 'HotelSystem.GlobalVariables.customer'
检查登录日志和客户类的声明。它们前面可能缺少public关键字,因此默认情况下它们是内部的,因此不易访问。

检查登录日志和客户类的声明。它们前面可能缺少public关键字,因此默认情况下它们是内部的,因此不易访问。

该错误意味着您的客户和登录日志类型比使用它们的字段更难访问,即它们不是公共的

字段的类型必须至少与字段本身一样可访问。将客户和登录日志公开应该可以解决此错误。

此错误意味着您的客户和登录日志类型比使用它们的字段更难访问,即它们不是公开的


字段的类型必须至少与字段本身一样可访问。将客户和登录日志公开应该可以解决此错误。

您是否尝试过错误所说的内容


将“public”添加到登录日志类和客户类中

您是否尝试了错误所说的内容


将“public”添加到登录日志类和客户类中

您可以将您的globals类设置为内部并使用属性,这通常更为惯用,因为它更安全,便于将来验证您的API:

internal static class GlobalVariables
{
    private static readonly login_log cashier = new login_log();
    private static readonly List<customer> customer = new List<customer>();

    public static login_log Cashier { get { return cashier; } }
    public static IList<customer> Customer { get { return customer; } }
}
这将导致可访问性与其他类相同


请注意,将登录日志和客户公开也可以解决此问题。但是,虽然我不建议一般地创建这种性质的静态全局数据,但如果要这样做,将其保存在程序集中的内部可能比将其公开要好。

您可以将globals类设置为内部并使用属性,这通常更惯用,因为它更安全,便于将来验证您的API:

internal static class GlobalVariables
{
    private static readonly login_log cashier = new login_log();
    private static readonly List<customer> customer = new List<customer>();

    public static login_log Cashier { get { return cashier; } }
    public static IList<customer> Customer { get { return customer; } }
}
这将导致可访问性与其他类相同


请注意,将登录日志和客户公开也可以解决此问题。然而,虽然我不建议一般地创建这种性质的静态全局数据,但如果要这样做,将其保存在程序集中内部可能比将其公开要好。

臭烘烘的静态全局变量。臭烘烘的静态全局变量。使这两个类更容易访问似乎是一个糟糕的选择,当另一个选项是使此全局数据更难访问时,越隐藏越好..使这两个类更容易访问似乎是一个糟糕的选择,当另一个选项是使此全局数据更难访问时,越隐藏越好..+1对于内部-这是更干净的全局方法。但拥有全球数据仍然不是一个好主意。@Eval不能同意更多的观点——将事情公开只是为了让全球数据发挥作用dirty@LewsTherinconst不起作用,但它们可以是只读的——我更喜欢道具,尽管是这样。因为新的关键字。是的,只读,然后使用私有静态构造函数。是的,道具虽然可能需要使用私人设置@卢瑟林:那更好吗+1对于内部-这是做全局的更干净的方法。但拥有全球数据仍然不是一个好主意。@Eval不能同意更多的观点——将事情公开只是为了让全球数据发挥作用dirty@LewsTherinconst不起作用,但它们可以是只读的——我更喜欢道具,尽管是这样。因为新的关键字。是的,只读,然后使用私有静态构造函数。是的,道具虽然可能需要使用私人设置@卢瑟林:那更好吗