隐阵铸造在C# [英] Implicit array casting in C#

查看:137
本文介绍了隐阵铸造在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有定义的隐式转换操作符以下类:

I have the following classes with an implicit cast operator defined:

class A
{
    ...
}
class B
{
    private A m_a;

    public B(A a)
    {
        this.m_a = a;
    }

    public static implicit operator B(A a)
    {
        return new B(a);
    }
}

现在,我可以隐式转换A到B

Now, I can implicitly cast A to B.

但是,为什么我不能隐式转换A []到B []?

But why can't I implicitly cast A[] to B[] ?

static void Main(string[] args)
{
    // compiles
    A a = new A();
    B b = a;

    // doesn't compile
    A[] arrA = new A[] {new A(), new A()};
    B[] arrB = arrA;
}

谢谢,马勒基。

推荐答案

由于迈赫达德Afshari提到的,​​你的运气含蓄地这样做的。你必须得到明确的,它会涉及到一个数组的副本。幸运的是,你也许可以与一个一行做到这一点:

As Mehrdad Afshari mentioned, you're out of luck doing this implicitly. You'll have to get explicit, and it'll involve an array copy. Thankfully, you can probably do it with a one-liner:

arrB = arrA.Cast<B>().ToArray();

但如果你只想迭代 ARRB 的foreach 语句,则可以省略避免拷贝 ToArray的()

Although if you only want to iterate arrB in a foreach statement, you can avoid the copy by omitting ToArray()

这篇关于隐阵铸造在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆