【问题标题】:How to reference global static Dictionary without class name?如何引用没有类名的全局静态字典?
【发布时间】:2014-07-31 16:01:43
【问题描述】:

我有一个名为 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"},
    };
}

来自Main.cs,我不得不像这样引用它:

new MySqlCommand(SQL.SQL["Customers"]);

如何消除第一个SQL? IE。我想使用:

new MySqlCommand(SQL["Customers"]);

【问题讨论】:

  • 您最好使用资源文件,如果您使用 Winforms 则使用 resx 文件,如果使用 WPF 则使用 ResourceDictionary

标签: c# .net static global


【解决方案1】:

使用const string 而不是Dictionary 可能会更好。然后您可以轻松引用它们并获得编译时错误。

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

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

【讨论】:

  • 这种模式有名字吗?我正在一个涉及自定义 USB 协议的项目中做这件事。
【解决方案2】:

目前,您无法执行此操作。如果静态索引器是可能的,你可以,但它们不是。

在 C# 6.0 中,这将通过静态 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"},
        };
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    相关资源
    最近更新 更多