gpt4 book ai didi

c# - 一个类型的多个索引属性?

转载 作者:太空狗 更新时间:2023-10-29 20:01:58 26 4
gpt4 key购买 nike

在 C# 中有可能有这样的东西吗?我不是很确定:

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"] = ...

所以我需要在我的框架中实现(通过调用它们)的完整成员方法是:

GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)

我想在我自己的类型中更清晰地实现它们。

最佳答案

你能做到这一点的唯一方法是拥有 Books是一个返回类型的属性,该类型具有自己合适的索引器。这是一种可能的方法:

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<,> 的实现而不是使用这种方法,因为它会允许其他漂亮的东西,比如键值对的枚举等。

关于c# - 一个类型的多个索引属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4730239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com