我有一个包含参数字典的类:
public class Parameter : IExecutionParameter, IDesignerParameter
{
}
public interface IExecutionSettings
{
IDictionary<string, IExecutionParameter> Parameters { get; }
}
public interface IDesignerSettings
{
IDictionary<string, IDesignerParameter> Parameters { get; }
}
public class Settings : IExecutionSettings, IDesignerSettings
{
private Dictionary<string, Parameter> _parameters;
// TODO: Implement IExecutionSettings.Parameters
// TODO: Implement IDesignerSettings.Parameters
}
我想创建这些接口(interface)的显式实现(我知道该怎么做),但我不知道如何正确转换字典。
我们将不胜感激。
最佳答案
你不能,因为那样不安全。假设你可以投 Dictionary<string, MemoryStream>
至 IDictionary<string, IDisposable>
- 然后你就可以输入任何 IDisposable
通过后一个引用在字典中的值,即使实际字典只能容纳 MemoryStream
-兼容引用。
您可能会创建一个只读字典包装器,它将所有读取委托(delegate)给底层字典,并在所有写入时失败。然后你可以包装你的 Dictionary<string, Parameter>
在其中两个“ View ”词典中。这会有点痛苦,但可行。在您的情况下这是否是最合适的方法是另一回事。
也许你应该:
public interface IExecutionSettings
{
IExecutionParameter this[string key] { get; }
}
public interface IDesignerSettings
{
IDesignerParameter this[string key] { get; }
}
您可以轻松地(明确地)在 Settings
中实现这两个功能.
关于c# - 将 Dictionary<string, class> 转换为 IDictionary<string, interface>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9034525/