我有一个名为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
?即我想用:
new MySqlCommand(SQL["Customers"]);
答案 0 :(得分:4)
使用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);
答案 1 :(得分:3)
目前,你无法做到这一点。你可以使用静态索引器,但它们不是。
在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"},
};
}
}