我有一个像这样从 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/