如何将System.Array转换为System.Collections.Immutable.ImmutableArray?

5
当我尝试进行隐式转换时,会出现以下错误:
Cannot implicitly convert type 'System.Array' to 'System.Collections.Immutable.ImmutableArray<Type>'

当我尝试进行显式类型转换时,出现以下错误:

Cannot convert type 'System.Array' to 'System.Collections.Immutable.ImmutableArray'

Cannot convert to static type 'System.Collections.Immutable.ImmutableArray'

2
看起来你把 ImmutableArrayImmutableArray<T> 搞混了,但是因为你没有展示任何代码,所以很难说。 - user5090812
你说得对,谢谢。 - Anthony
4个回答

5

这是我最终使用的。谢谢。我还有另一个问题,就是我在使用 System.Array 与 MyType[]。 - Anthony

0

IReadOnlyCollection 是你要找的。


0
在.NET 8预览版中,有几种新的方法可以访问内部构造函数,因此具有高性能且无内存消耗。
使用ImmutableCollectionsMarshal.AsImmutableArray<T>
ImmutableArray<T> im = ImmutableCollectionsMarshal.AsImmutableArray(array);

这是标杆 - 聪明是新的方式。

enter image description here


0
public static ImmutableArray<T> Create<T>(T[] items)
            {

                if (items.length == 0)
                {
                    // Avoid allocating an array.
                    return Create<T>();
                }

                var array = new T[items.length];
                for (int i = 0; i < items.length; i++)
                {
                    array[i] = items[i];
                }

                return new ImmutableArray<T>(array);
            }

使用上述代码,您可以创建一个ImmutableArray。通过调用

return Create(yourArrayHere);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接