gpt4 book ai didi

c# - C# 中的显式对象数组类型转换?

转载 作者:太空狗 更新时间:2023-10-30 00:58:58 24 4
gpt4 key购买 nike

如果我有两个类,并且在它们之间定义了显式类型转换,我是否不能将一个类的数组转换为另一个类的数组?

即。

using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Apple ted = new Apple() { Variety = Apple.EVariety.RedEllison };
Orange bob = (Orange)ted; // explicit type conversion

Apple[] apples = new Apple[] { ted };
Orange[] oranges = new Orange[1];

//oranges = apples; // why is this illegal ?

// is this better ?
oranges = Array.ConvertAll<Apple, Orange>(apples, new Converter<Apple, Orange>(p => (Orange)p));
}

class Apple
{
public enum EVariety { RedEllison, GrannySmith }
public EVariety Variety;
}

class Orange
{
enum EColour { Unknown, Red, Green }
EColour Colour;

public static explicit operator Orange(Apple apple)
{
Orange result = new Orange();
result.Colour = apple.Variety == Apple.EVariety.RedEllison ? result.Colour = EColour.Red : result.Colour = EColour.Green;
return result;
}
}
}
}

谢谢,罗斯

最佳答案

只有在源类型和目标类型之间存在引用转换时,转换才有效 - 换句话说,数组中的每个元素都可以用作任何一种类型,而无需更改数据。

来自 C# 规范,第 6.2.4 节(显式引用转换):

The explicit reference conversions are:

...

  • From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true:
    • S and T differ only in element type. In other words, S and T have the same number of dimensions.
    • Both SE and TE are reference-types.
    • An explicit reference conversion exists from SE to TE.

在我看来,Array.ConvertAll 绝对是解决此问题的方法,但您应该能够使用类型推断使它变得更好:

oranges = Array.ConvertAll(apples, p => (Orange)p);

关于c# - C# 中的显式对象数组类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1661127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com