我有一些已经定义好的扩展方法,例如:
public static object Get(this IDictionary<string, object> dict, string key)
{
if (dict.TryGetValue(key, out object value))
{
return value;
}
return null;
}
但是如果我尝试将其与
的实例一起使用IDictionary <string, myClass>
它不会显示。我以为每个类都是从对象派生的。问题:
1)为什么会这样?
2)我如何制作一个包含各种IDictionary的扩展方法?
答案 0 :(得分:1)
这很正常:
using System.Collections.Generic;
namespace ConsoleApp1
{
public class Program
{
public static void Main(string[] args)
{
var dic = new Dictionary<string, object> {{"Test", 1}};
var result = dic.Get("Test");
}
}
public static class MyExtensions
{
public static object Get(this IDictionary<string, object> dict, string key)
{
if (dict.TryGetValue(key, out object value))
{
return value;
}
return null;
}
public static T Get<T>(this IDictionary<string, T> dict, string key)
{
if (dict.TryGetValue(key, out T value))
{
return value;
}
return default(T);
}
}
}