创建带有字典参数的方法,其中TKey和TValue类型是不确定的

想知道是否可能有一个带有字典参数的方法,其中TKey和TValue类型是不确定的。例如,我可能要发送一个int的键和一个值作为自定义对象,或者发送一个字符串和另一个对象的值的键。


可以通过通用对象完成此操作吗,是重载的最佳实践,还是我还没有找到其他方法?


public static SortedDictionary<??, ??> CreateSortedDictionary(Dictionary<??, ??> d)

{

    SortedDictionary<??, ??> rv = new SortedDictionary<??, ??>();


    enter code here...


    return rv;

}


SMILET
浏览 158回答 1
1回答

慕桂英3389331

您可以将通用类型用于键和值,然后将其用于输入和输出字典:public static SortedDictionary<TKey, TValue> CreateSortedDictionary<TKey, TValue>(&nbsp; &nbsp; Dictionary<TKey, TValue> input){&nbsp; &nbsp; return new SortedDictionary<TKey, TValue>(input);}
打开App,查看更多内容
随时随地看视频慕课网APP