不能对 IDictionary<string, object> 使用扩展方法
Cannot use extension method for IDictionary<string, object>
我已经定义了一些这样的扩展方法:
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>
它不会出现。我认为每个 class 派生自对象。问题:
1) 为什么会这样?
2) 如何制作包含各种 IDictionary 的扩展方法?
这非常有效:
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);
}
}
}
我已经定义了一些这样的扩展方法:
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>
它不会出现。我认为每个 class 派生自对象。问题:
1) 为什么会这样?
2) 如何制作包含各种 IDictionary 的扩展方法?
这非常有效:
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);
}
}
}