为什么静态索引在C#中不允许?我不明白为什么他们不应该被允许的,而且他们可能是非常有用的。
Why are static indexers disallowed in C#? I see no reason why they should not be allowed and furthermore they could be very useful.
例如:
static class ConfigurationManager {
public object this[string name]{
get{
return ConfigurationManager.getProperty(name);
}
set {
ConfigurationManager.editProperty(name, value);
}
}
/// <summary>
/// This will write the value to the property. Will overwrite if the property is already there
/// </summary>
/// <param name="name">Name of the property</param>
/// <param name="value">Value to be wrote (calls ToString)</param>
public static void editProperty(string name, object value) {
DataSet ds = new DataSet();
FileStream configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);
ds.ReadXml(configFile);
if (ds.Tables["config"] == null) {
ds.Tables.Add("config");
}
DataTable config = ds.Tables["config"];
if (config.Rows[0] == null) {
config.Rows.Add(config.NewRow());
}
if (config.Columns[name] == null) {
config.Columns.Add(name);
}
config.Rows[0][name] = value.ToString();
ds.WriteXml(configFile);
configFile.Close();
}
public static void addProperty(string name, object value) {
ConfigurationManager.editProperty(name, value);
}
public static object getProperty(string name) {
DataSet ds = new DataSet();
FileStream configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);
ds.ReadXml(configFile);
configFile.Close();
if (ds.Tables["config"] == null) {
return null;
}
DataTable config = ds.Tables["config"];
if (config.Rows[0] == null) {
return null;
}
if (config.Columns[name] == null) {
return null;
}
return config.Rows[0][name];
}
}
以上code将极大地从一个静态的索引中获益。然而,它不能编译,因为静态的索引是不允许的。为什么会这样?
The above code would benefit greatly from a static indexer. However it won't compile because static indexers are not allowed. Why is this so?
索引符号要求引用这
。由于静态方法不具有参考类的特定实例,你不能使用这
和他们在一起,因此不能在静态使用索引符号的方法。
Indexer notation requires a reference to this
. Since static methods don't have an reference to a particular instance of the class, you can't use this
with them, and consequently you can't use indexer notation on static methods.
该问题的解决方案是使用Singleton模式如下:
The solution to your problem is using a singleton pattern as follows:
public class Utilities
{
static ConfigurationManager _configurationManager = new ConfigurationManager();
public static ConfigurationManager ConfigurationManager
{
get
{
return _configurationManager;
}
}
}
public class ConfigurationManager
{
public object this[string value]
{
get
{
return new object();
}
set
{
// set something
}
}
}
现在你可以叫 Utilities.ConfigurationManager [someKey]
使用索引符号。
Now you can call Utilities.ConfigurationManager["someKey"]
using indexer notation.