gpt4 book ai didi

c# - 为什么不能在 .NET 中定义通用索引器?

转载 作者:IT王子 更新时间:2023-10-29 03:55:26 26 4
gpt4 key购买 nike

为什么不能在 .NET 中创建通用索引器?

以下代码会引发编译错误:

public T this<T>[string key]
{
get => /* Return generic type T. */
}

这是否意味着您不能为通用成员集合创建通用索引器?

最佳答案

这是一个有用的地方。假设你有一个强类型的 OptionKey<T>用于声明选项。

public static class DefaultOptions
{
public static OptionKey<bool> SomeBooleanOption { get; }
public static OptionKey<int> SomeIntegerOption { get; }
}

通过 IOptions 公开选项的位置接口(interface):

public interface IOptions
{
/* since options have a default value that can be returned if nothing's
* been set for the key, it'd be nice to use the property instead of the
* pair of methods.
*/
T this<T>[OptionKey<T> key]
{
get;
set;
}

T GetOptionValue<T>(OptionKey<T> key);
void SetOptionValue<T>(OptionKey<T> key, T value);
}

然后代码可以使用通用索引器作为一个很好的强类型选项存储:

void Foo()
{
IOptions o = ...;
o[DefaultOptions.SomeBooleanOption] = true;
int integerValue = o[DefaultOptions.SomeIntegerOption];
}

关于c# - 为什么不能在 .NET 中定义通用索引器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/494827/

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