Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何引用没有类名的全局静态字典?_C#_.net_Static_Global - Fatal编程技术网

C# 如何引用没有类名的全局静态字典?

C# 如何引用没有类名的全局静态字典?,c#,.net,static,global,C#,.net,Static,Global,我有一个名为SQL.cs的文件,为了简洁起见,它看起来像这样: using System.Collections.Generic; public static class SQL { public static readonly Dictionary<string, string> SQL = new Dictionary<string, string>() { {"Customers", "SELECT * FROM cus

我有一个名为SQL.cs的文件,为了简洁起见,它看起来像这样:

using System.Collections.Generic;

public static class SQL
{
    public static readonly Dictionary<string, string> SQL = new Dictionary<string, string>()
    {
        {"Customers",       "SELECT * FROM customers"},
        {"OverdueInvoices", "SELECT * FROM invoices WHERE overdue = true"},
    };
}
如何消除第一个SQL?即,我想使用:

new MySqlCommand(SQL["Customers"]);

目前,您不能这样做。如果静态索引器是可能的,您可以这样做,但事实并非如此

在C 6.0中,这将通过static using语句提供

此代码在Visual Studio 2014 CTP 2中编译:

using System.Collections.Generic;
using ConsoleApplication2.SQL;

namespace ConsoleApplication2
{
    class Program
    {
        public static void Main(string[] args)
        {
            string command = Commands["Customers"];
        }
    }

    public static class SQL
    {
        public static readonly Dictionary<string, string> Commands = new Dictionary<string, string>()
        {
            {"Customers",       "SELECT * FROM customers"},
            {"OverdueInvoices", "SELECT * FROM invoices WHERE overdue = true"},
        };
    }
}

使用常量字符串可能比使用字典更好。然后您可以很容易地引用它们,并得到编译时错误

public static class SQL
{
    public const string Customers = @"SELECT * FROM Customers";
}

//Wherever you're going to use it
new MySqlCommand(SQL.Customers);

这个图案有名字吗?我正是在一个涉及自定义USB协议的项目中做这件事的。您最好使用一个资源文件,如果您使用的是Winforms,则使用resx文件;如果您使用的是WPF,则使用ResourceDictionary文件。
public static class SQL
{
    public const string Customers = @"SELECT * FROM Customers";
}

//Wherever you're going to use it
new MySqlCommand(SQL.Customers);