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;}
}
}
So it could be used as such:
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.
Like functions, Indexers can also be overloaded. In C#, we can have multiple indexers in a single class. To overload an indexer, declare it with multiple parameters and each parameter should have a different data type. Indexers are overloaded by passing 2 different types of parameters.
An indexed property is a variable property that serves as a selection filter for active processes. It can also be used in defining events for business event processing. This property holds a piece of data, such as a customer Id, application date, or amount.
Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.
An indexer allows you to access a class instance in terms of a member array. An indexer declaration may include a set of attributes; a new modifier; a valid combination of the public, private, protected, and internal access modifiers; and one of the virtual, override, or abstract modifiers.
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With