c# 无法将类型隐式转换_C#中的隐式类型数组

c# 无法将类型隐式转换

C#隐式类型数组 (C# Implicitly Typed Arrays)

Like implicitly typed variables, we can also declare an array without specifying its type such type of arrays are known as Implicitly typed arrays.

隐式类型的变量一样,我们也可以在不指定其类型的情况下声明一个数组,这样的数组类型称为隐式类型的数组

The type of the array is determined by the compiler based on the initializer list.

数组的类型由编译器根据初始化列表确定。

Syntax:

句法:

    var array_name = new[] {initialize_list/elements};

Example:

例:

    var arr1 = new[] { 10, 20, 30, 40, 50 };
    var arr2 = new[] { 10.0f, 20.1f, 30.2f, 40.3f, 50.4f };
    var arr3 = new[] { "Manju", "Amit", "Abhi", "Radib", "Prem" };

Here, arr1 will be determined as int[] (integer array), arr2 as float[] (float/single array), and arr3 as String[] (string array).

在这里,将arr1确定为int [] (整数数组),将arr2确定为float [] (浮点数/单数组),将arr3确定为String [] (字符串数组)。

C#代码演示隐式类型数组的示例 (C# code to demonstrate example of implicitly typed arrays )

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr1 = new[] { 10, 20, 30, 40, 50 };
            var arr2 = new[] { 10.0f, 20.1f, 30.2f, 40.3f, 50.4f };
            var arr3 = new[] { "Manju", "Amit", "Abhi", "Radib", "Prem" };

            //printing type of the array
            Console.WriteLine("Type of arr1: " + arr1.GetType());
            Console.WriteLine("Type of arr2: " + arr2.GetType());
            Console.WriteLine("Type of arr3: " + arr3.GetType());

            //printing the elements
            Console.WriteLine("arr1 elements...");
            foreach (var item in arr1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine("arr2 elements...");
            foreach (var item in arr2)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            Console.WriteLine("arr3 elements...");
            foreach (var item in arr3)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

输出量

Type of arr1: System.Int32[]
Type of arr2: System.Single[]
Type of arr3: System.String[]
arr1 elements...
10 20 30 40 50
arr2 elements...
10 20.1 30.2 40.3 50.4
arr3 elements...
Manju Amit Abhi Radib Prem


翻译自: https://www.includehelp.com/dot-net/implicitly-typed-arrays-in-c-sharp.aspx

c# 无法将类型隐式转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值