标签: generic-collections

为什么C#不支持泛型泛型(带参数化类型的泛型)?

最近(可能是设计缺点)当我需要有一个未修复的MyType<T>地方集合时T(即整个集合中有多个不同的泛型实例),我遇到了常规任务.

由于它被广泛提出(对于这种情况),宣布了一个抽象类:

public abstract class MyType {}
public class MyType<T>: MyType {}
Run Code Online (Sandbox Code Playgroud)

然后我收集了一些MyType.但是对于这个集合,我有一个约束,即任何类型的元素都不超过一个T.

因此,我做了一些自定义实现ICollection<TBase>.我想在其中包含一个Get<TParam>()获取与类型对应的项的方法TParam.以后用作:

MyCollection<MyType> collection = new MyCollection<MyType>();
MyType<int> myInt = collection.Get<int>();
Run Code Online (Sandbox Code Playgroud)

但是我意外地发现我甚至无法宣布它:

public TCustom<TParam> Get<TParam, TCustom<TParam>>() { } //this won't compile
Run Code Online (Sandbox Code Playgroud)

因为内部泛型(或所谓的"泛型泛型")既不支持C#也不支持.NET(我想).您如何看待这些限制背后是否存在任何具体原因(复杂性除外)?

更新1.询问编译器版本和编译器错误.

Microsoft C#,.NET 3.5(Visual Studio 2010).错误:

错误CS0081:类型参数声明必须是标识符而不是类型

错误CS0246:找不到类型或命名空间名称"TCustom"(您是否缺少using指令或程序集引用?)

更新2.被问及我是否需要修复或解释原因.我真的想知道为什么.但如果你有解决问题的好方法,也欢迎你.

更新3. 此博客文章中可能已经回答了这个问题.似乎CLR团队面临着不要过度复杂化语言的巨大压力.

.net c# generics generic-collections nested-generics

5
推荐指数
1
解决办法
428
查看次数

在.net4中使用动态泛型集合时无法理解异常

请检查以下代码:

static void Main(string[] args) {
    IList<dynamic> items = new List<dynamic>();
    items.Add(3);
    items.Add("solid");
    dynamic i = new ExpandoObject();
    items.Add(i); //System.Collections.Generic.IList<object>' does not contain a definition for 'Add'
    Console.WriteLine();
}
Run Code Online (Sandbox Code Playgroud)

这是"动态"机制中的错误吗?

dynamic .net-4.0 generic-collections

5
推荐指数
1
解决办法
1303
查看次数

具有宏的类型安全的通用容器

我正在尝试使用宏在C中创建一个类型安全的通用链表.它应该与模板在C++中的工作方式类似.例如,

LIST(int) *list = LIST_CREATE(int);
Run Code Online (Sandbox Code Playgroud)

我的第一次尝试是#define LIST(TYPE)(我上面使用的宏)定义一个struct _List_##TYPE {...}.但是,这不起作用,因为每次我声明一个新列表时都会重新定义结构.我通过这样做解决了这个问题:

/* You would first have to use this macro, which will define
   the `struct _List_##TYPE`...                               */
DEFINE_LIST(int);

int main(void)
{
    /* ... And this macro would just be an alias for the struct, it
       wouldn't actually define it.                                  */
    LIST(int) *list = LIST_CREATE(int);
    return 0;
}

/* This is how the macros look like */

#define DEFINE_LIST(TYPE)    \
    struct _List_##TYPE      \
    {                        \
        ...                  \
    }

#define …
Run Code Online (Sandbox Code Playgroud)

c macros containers generic-collections

5
推荐指数
2
解决办法
3141
查看次数

通用集合类型测试

我想根据给定的集合类型(使用反射)进行一些操作,而不管泛型类型.

这是我的代码:

    void MyFct(Type a_type)
    {
        // Check if it's type of List<>
        if (a_type.Name == "List`1")
        {
            // Do stuff
        }
        // Check if it's type of Dictionary<,>
        else if (a_type.Name == "Dictionary`2")
        {
            // Do stuff
        }
    }
Run Code Online (Sandbox Code Playgroud)

它现在有效,但对我来说很明显,它不是最安全的解决方案.

    void MyFct(Type a_type)
    {
        // Check if it's type of List<>
        if (a_type == typeof(List<>))
        {
            // Do stuff
        }
        // Check if it's type of Dictionary<,>
        else if (a_type == typeof(Dictionary<,>))
        {
            // Do stuff
        }
    }
Run Code Online (Sandbox Code Playgroud)

我也试过,它实际编译但不起作用...我也尝试测试给定集合类型的所有接口,但它暗示了集合中接口的排他性...... …

c# types generic-collections

5
推荐指数
1
解决办法
802
查看次数

如何增加分配的内存?{由于内存不足异常,功能评估被禁用.}

我的目标是使用C#ASP.NET MVC从XML文件加载148万个项目到内存通用集合字典,并能够将过滤器列表呈现给视图.现在它在VS调试模式下作为单个用户在我的字典中使用大约50万个项目.我得到了更多的内存错误 - 现在我得到:myDictionary.Count导致System.TypeInitializationException - '由于内存不足异常,函数评估已被禁用.

在过去,从XML到Dict的加载过程中也出现了mscorlib.dll,它抱怨了内存不足.

我还有足够的系统内存,如何为这个MVC Web应用程序提供更多内容?顺便说一句,我尝试使用XML到Perl词典,它可以很好地处理150万个对象 - 没问题.我不想在Perl中编写我的应用程序.如果Perl可以做到这一点,C#必须能够做到 - 我还没有找到一个搜索网络的解决方案.

示例代码:

Dictionary<string, msg> masterDictionary = new Dictionary<string, mgs>();

foreach (string file in filePath)
{
    XDocument xdoc = XDocument.Load(file);
    Dictionary<string, msg> fileDictionary = xdoc
        .Descendants("msg")
        .ToDictionary(m => m.Element("msgId").Value,
                      m => new msg
                           {
                               msgId = m.Element("msgId").Value,
                               msgType = m.Element("msgType").Value,
                               name = m.Element("name").Value
                           });

    //now insert your new values into the master
    foreach(var newValue in fileDictionary)
        masterDictionary.Add(newValue.Key, newValue.Value);
}
Run Code Online (Sandbox Code Playgroud)

c# memory asp.net-mvc memory-management generic-collections

5
推荐指数
1
解决办法
1万
查看次数

我的IEquatable仍在使用Object.GetHashcode作为Dictionary &lt;T&gt; []

我有以下类似内容,是通用词典的关键。

class IMyClass<T> : IEquatable<IMyClass> where T : struct
{
  //etc
}


class MyClass<T> : IMyClass<T> where T : struct
{
    public bool Equals(IRatingKey<T> other)
    {
       //etc
    }
}
Run Code Online (Sandbox Code Playgroud)

据我了解EqualityComparer<T>.Default,应该看到我已经实现IEquatable<T>并因此动态创建了一个EqualityComparer。

Dictionary<TKey, TValue>需要一个相等的实现来确定键是否相等。如果comparer为null,则此构造方法使用默认的泛型相等比较器 EqualityComparer<T>.Default。如果type TKey实现了 System.IEquatable<T>通用接口,则默认的相等比较器将使用该实现。

但是从我使用字典索引器的角度来看Dictionary<T>[],它仍然依赖于覆盖GetHashcode例如public override int GetHashCode()

我可以看到有一些建议可以覆盖很多内容,以保持一致性,但是我想进一步理解它。是因为IEquatable应该直接在MyClass而不是IMyClass上吗?但我希望在IMyClass上使用它,因此实现者需要是字典键。

我正在尝试IEqualityComparer,但据我了解,我不需要它。

c# dictionary iequatable generic-collections c#-4.0

5
推荐指数
1
解决办法
416
查看次数

为什么IList <T>实现IEnumerable <T>和ICollection <T>而ICollection <T>本身实现IEnumerable <T>

为什么IList这样定义?

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable

public interface ICollection<T> : IEnumerable<T>, IEnumerable

public interface IEnumerable<T> : IEnumerable
Run Code Online (Sandbox Code Playgroud)

不可能只是

public interface IList<T> : ICollection<T>
Run Code Online (Sandbox Code Playgroud)

所以,为了测试我创建了这些接口,只是为了确定它是否有效!

public interface IOne
{
    string One();
}

public interface ITwo : IOne
{
    string Two();
}

public interface IThree : ITwo, IOne
{
    string Three();
}
Run Code Online (Sandbox Code Playgroud)

虽然它很好,Resharper抱怨"冗余接口".

微软继续这个实现的任何想法?

.net c# ilist generic-list generic-collections

5
推荐指数
1
解决办法
880
查看次数

无法将List &lt;List &lt;int &gt;&gt;转换为返回类型IList &lt;IList &lt;int &gt;&gt;

对于级别顺序遍历,为什么会发生此异常?发生以下异常:

无法将类型' System.Collections.Generic.List<System.Collections.Generic.List<int>>' 隐式转换为' System.Collections.Generic.IList<System.Collections.Generic.IList<int>>'。存在显式转换(您是否缺少演员表?)

public IList<IList<int>> LevelOrder(TreeNode root) 
{
    var result = new List<List<int>>();
    var que = new Queue<TreeNode>();

    //if(root==null) return result;

    que.Enqueue(root);
    while(que.Count!=0)
    {
        int n = que.Count;
        var subList = new List<int>();
        for(int i=0;i<n;i++)
        {
            if(que.Peek().left!=null) 
                que.Enqueue(que.Peek().left);
            if(que.Peek().right!=null)
                que.Enqueue(que.Peek().right);
            subList.Add(que.Dequeue().val);
        }
        result.Add(subList);
    }
    return  result;
}
Run Code Online (Sandbox Code Playgroud)

.net c# generics list generic-collections

5
推荐指数
1
解决办法
1474
查看次数

实现 TObjectList&lt;myClass&gt; 的自定义二进制搜索 (Delphi XE)

我需要在使用自定义比较器的 TObjectList 上实现二分搜索,我相信使用 TCustomComparer。

目标:二分查找返回列表中符合特定属性参数的实例。

例如:

TMyClass=class
    public
     Index:integer
end;

TMyObjectList=TObjectList<TMyClass>;

begin
  ...
    aMyClass.Index:=1;
    aMyObjectList.binarysearch(aMyClass, aMyClassRef) 
  ...
end;
Run Code Online (Sandbox Code Playgroud)

或者简单地:

 begin
   ...
     aMyObjectList.binarysearch(1, aMyClassRef) 
   ...
 end;
Run Code Online (Sandbox Code Playgroud)

我想循环并获取列表中也具有 Index==1 的 TMyClass 实例。

在 C++ 中,重载“==”运算符可以实现此目标。

新的 Delphi“帮助”相当稀疏且分散,使得东西很难找到,而且我不太熟悉新的 Delphi 泛型的所有细微差别。

那么 - 我如何在 Delphi XE 中使用 Generics.TObjectList 来做到这一点?

(使用德尔福XE)。

TIA

delphi binary-search generic-collections delphi-xe

4
推荐指数
1
解决办法
2397
查看次数

collections.abc.Sequence 和打字.Sequence 之间的区别

我正在阅读一篇关于 collection.abc 和 python 标准库中的类型类的文章,发现这两个类具有相同的功能。

我使用下面的代码尝试了这两个选项并得到了相同的结果

from collections.abc import Sequence

def average(sequence: Sequence):
    return sum(sequence) / len(sequence)

print(average([1, 2, 3, 4, 5]))  # result is 3.0

from typing import Sequence

def average(sequence: Sequence):
    return sum(sequence) / len(sequence)

print(average([1, 2, 3, 4, 5])) # result is 3.0


Run Code Online (Sandbox Code Playgroud)

在什么情况下,collection.abc 会成为更好的打字选择。使用其中一种比另一种有好处吗?

python generic-collections python-3.x python-typing

4
推荐指数
1
解决办法
4866
查看次数