类型上有多个索引属性? [英] Multiple index properties on a type?
问题描述
在C#中是否可能有类似的东西?我不太确定:
Is it possible to have something like this in C#? I am not very sure:
class Library
{
public string Books[string title]
{
get{return this.GetBookByName(string title);}
}
public DateTime PublishingDates[string title]
{
get{return this.GetBookByName(string title).PublishingDate;}
}
}
因此可以这样使用:
myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...
因此,我需要在我的框架中(通过调用它们)实现的完整成员方法是:
So my complete member methods that I need to implement in my framework (by calling them) are:
GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)
我想以自己的类型将它们实现得更干净.
I want to implement them cleaner in my own type.
推荐答案
唯一的方法是让 Books
是一个属性,该属性返回具有自己合适的索引器的类型.这是一种可能的方法:
The only way you could do this would be to have Books
be a property that returns a type that has its own suitable indexer. Here's one possible approach:
public class Indexer<TKey, TValue>
{
private Func<TKey, TValue> func;
public Indexer(Func<TKey, TValue> func)
{
if (func == null)
throw new ArgumentNullException("func");
this.func = func;
}
public TValue this[TKey key]
{
get { return func(key); }
}
}
class Library
{
public Indexer<string, Book> Books { get; private set; }
public Indexer<string, DateTime> PublishingDates { get; private set; }
public Library()
{
Books = new Indexer<string, Book>(GetBookByName);
PublishingDates = new Indexer<string, DateTime>(GetPublishingDate);
}
private Book GetBookByName(string bookName)
{
// ...
}
private DateTime GetPublishingDate(string bookName)
{
return GetBookByName(bookName).PublishingDate;
}
}
但是您应该认真考虑提供 IDictionary<>
的实现,而不是使用这种方法,因为它会允许其他一些漂亮的东西,例如键值对的枚举等.
But you should seriously consider providing an implementation of IDictionary<,>
instead of using this approach, as it will allow other nifty stuff, like enumeration of key-value pairs, etc.
这篇关于类型上有多个索引属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!