【问题标题】:using collection in generic function在泛型函数中使用集合
【发布时间】:2019-09-06 07:10:59
【问题描述】:

我试图对 2 种集合使用通用函数,我在其中调用方法 Add。

所以在我的代码下面:

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void AddElement<T>(ref T container, string key, string value)
        {
            container.Add(key, value);
        }

        static void Main(string[] args)
        {
            SortedList s1 = new SortedList();
            Hashtable  h1 = new Hashtable();

            AddElement<SortedList>(ref s1, "001", "Zara Ali");
            AddElement<Hashtable>(ref h1, "001", "Zara Ali");
        }
    }
}

及以下错误:

错误 CS1061:“T”不包含“添加”的定义,并且没有 扩展方法“添加”接受“T”类型的第一个参数

那么这可以执行吗?如果可能的话如何解决?

提前谢谢你。

【问题讨论】:

  • 在不相关的注释中,ref 的使用是不必要的,因为您没有重新分配变量。
  • @pinkfloydx33 :对不起,我来自 C++,这是我第一次使用 C# 编程;)谢谢
  • 但实际上,这有什么意义呢?哪里有帮助(而不是使用已经定义的Add() 方法)?
  • @SeM 它不需要对我有帮助,我只是想操纵泛型和集合。定义添加作品:)。

标签: c# generics collections


【解决方案1】:

或者创建一个扩展方法:

public static class MyExtensions
{
    public static void AddElement(this IDictionary container, string key, string value)
    {
        container.Add(key, value);
    }
}

及用法:

SortedList s1 = new SortedList();
Hashtable h1 = new Hashtable();

s1.AddElement("001", "Zara Ali");
h1.AddElement("001", "Zara Ali");

【讨论】:

  • 不错,喜欢这种扩展方法的概念
【解决方案2】:

为什么不让它变得更容易呢?

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void AddElement(IDictionary container, string key, string value)
        {
            container.Add(key, value);
        }

        static void Main(string[] args)
        {
            SortedList s1 = new SortedList();
            Hashtable  h1 = new Hashtable();

            AddElement(s1, "001", "Zara Ali");
            AddElement(h1, "001", "Zara Ali");
        }
    }
}

【讨论】:

  • 是的,有道理 :) 我试图用集合操作一些泛型,但不知道 IDictionnary
【解决方案3】:

这里的问题是 T 可以是任何东西(例如一个 int)并且不能保证有一个 Add 方法。

您需要将 T 限制为具有 Add 方法的东西。

static void AddElement<T>(ref T container, string key, string value)
    where T : IDictionary 
{
    container.Add(key, value);
}

【讨论】:

  • IEnumerable 也不包含 Add。你需要非通用的IDictionary
猜你喜欢
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
相关资源
最近更新 更多