gpt4 book ai didi

c# - 使用 T 从 Dictionary 转换值

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:29 24 4
gpt4 key购买 nike

我有一个像这样从 Dictionary 继承的类

public class ManagedSettings : Dictionary<string, object>

因为我希望能够做到这一点

public object this[string key, bool myVar = true]
{
get{...}
set{...}
}

所以用户可以做

managerSettingVar["hisKey"] = hisValue;

但现在我想允许用户做这样的事情

managerSettingVar<bool>["hisKey"]

因此键“hisKey”的值已经转换为 bool 值。这甚至可能像我建议的那样吗?我尝试使用 T,但还不够幸运。有点像

public T this<T>[string key, bool myVar = true]

最佳答案

不,这是不可能的。索引器不能通用。

您可以创建一个通用的 GetValue 函数:

public T GetValue<T>(string key)
{
return Convert.ChangeType(this[key], typeof(T));
}

或者,只需要转换这些值:

public T GetValue<T>(string key)
{
return (T)this[key];
}

关于c# - 使用 T 从 Dictionary<string, object> 转换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16358000/

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