【问题标题】:Cannot use extension method for IDictionary<string, object>不能对 IDictionary<string, object> 使用扩展方法
【发布时间】:2019-11-19 03:35:08
【问题描述】:

我已经定义了一些类似这样的扩展方法:

    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 的扩展方法?

【问题讨论】:

  • 您想将它与非通用IDictionary 接口一起使用?顺便说一句,the indexer(例如dict[key])已经提供了你的扩展方法正在做的事情。
  • 请向我们提供minimal reproducible example 并实际告诉我们您遇到了什么错误。
  • 您的问题和目标不清楚。至于你正在发生或没有发生的事情。
  • 问题已更新。

标签: c# extension-methods


【解决方案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);
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 2018-08-05
相关资源
最近更新 更多