Mal*_*ist 114 .net c# static indexer static-indexers
为什么C#中不允许使用静态索引器?我认为没有理由不允许他们这样做,而且他们可能非常有用.
例如:
public static class ConfigurationManager
{
public object this[string name]
{
get => 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)
{
var ds = new DataSet();
var configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);
ds.ReadXml(configFile);
if (ds.Tables["config"] == null)
ds.Tables.Add("config");
var 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)
{
var ds = new DataSet();
var configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);
ds.ReadXml(configFile);
configFile.Close();
if (ds.Tables["config"] == null) return null;
var config = ds.Tables["config"];
if (config.Rows[0] == null) return null;
if (config.Columns[name] == null) return null;
return config.Rows[0][name];
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将从静态索引器中受益匪浅.但是它不会编译,因为不允许使用静态索引器.为什么会这样?
Jon*_*eet 88
我认为它被认为不是非常有用.我认为这也是一种耻辱 - 我倾向于使用的一个例子是编码,Encoding.GetEncoding("foo")可能在哪里Encoding["Foo"].我不认为这会拿出十分频繁,但除了别的它只是感觉有点不一致并不可用.
我必须检查,但我怀疑它已经在IL(中级语言)中可用.
Jul*_*iet 68
索引器表示法需要引用this.由于静态方法没有对类的特定实例的引用this,因此您不能使用它们,因此您不能在静态方法上使用索引符号.
问题的解决方案是使用单例模式,如下所示:
public class Utilities
{
private static ConfigurationManager _configurationManager = new ConfigurationManager();
public static ConfigurationManager ConfigurationManager => _configurationManager;
}
public class ConfigurationManager
{
public object this[string value]
{
get => new object();
set => // set something
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以Utilities.ConfigurationManager["someKey"]使用索引器表示法进行调用.
作为解决方法,您可以在单例/静态对象上定义实例索引器(假设ConfigurationManager是单例,而不是静态类):
class ConfigurationManager
{
//private constructor
ConfigurationManager() {}
//singleton instance
public static ConfigurationManager singleton;
//indexer
object this[string name] { ... etc ... }
}
Run Code Online (Sandbox Code Playgroud)