IDictionary<string, object> 和 IDictionary 之间的调用不明确

The call is ambiguous between IDictionary<string, object> and IDictionary

我正在使用一个带有 class 的库,它具有以下构造函数:

public JobDataMap(IDictionary<string, object> map);

public JobDataMap(IDictionary map);

我创建了一个 JobDataMap 实例:

var jdm = new JobDataMap(new Dictionary<String, Object> { 
  { "Manager", myObject } 
});

但是我遇到了编译错误:

The call is ambiguous between the following methods or properties:
'JobDataMap.JobDataMap(IDictionary<string, object>)' and 'JobDataMap.JobDataMap(IDictionary)' 

如何解决?

您可以将其转换为您希望它使用的构造函数的类型:

var jdm = new JobDataMap((IDictionary<string, object>) new Dictionary<String, Object> {
    { "Manager", new object() }
});

这个设计看起来确实有点可疑,但是...

您可以像这样强制传递类型:

var jdm = new JobDataMap((IDictionary<string, object>)new Dictionary<String, Object> { 
  { "Manager", myObject } 
});

或者您可以创建工厂方法并创建 non-generic 构造函数(我假设您较少使用它)private:

public class JobDataMap
{
    public JobDataMap(IDictionary<string, object> map)
    {
    }

    private JobDataMap(IDictionary map)
    {
    }

    public static JobDataMap FromNonGenericMap(IDictionary map)
    {
        return new JobDataMap(map);
    }
}

用法:

var jdm = JobDataMap.FromNonGenericMap(someNonGenericDictionary);

然后你可以像这样使用常规通用的:

var jdm = new JobDataMap(new Dictionary<String, Object> { 
  { "Manager", myObject } 
});