日期:2014-05-18  浏览次数:21285 次

C# 结构中的数组如何赋值?
C# code

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace TestCshap
{
    public struct Elem
    {
      public string [] name;
    }
    class Program
    {
        static void Main(string[] args)
        {
                Elem e = new Elem();
                e.name[0] = "fsdfsdfsdf";
                e.name[1] = "dad";
                Console.WriteLine(e.name[0]);
                Console.WriteLine(e.name[1]);
                 Console.ReadLine();
        }
    }
}
[color=#FF0000]如上C#代码, e.name[0] = "fsdfsdfsdf";这样做为什么要报错,难道不对吗?怎么改啊?[/color]




------解决方案--------------------
e.name = new string[10];//要先初始化大小
------解决方案--------------------
因为 public string [] name;没设置数组的长度
------解决方案--------------------
确定数组长度以后(假设长度为2)
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace TestCshap
{
public struct Elem
{
public string [] name=new string[2];
}
class Program
{
static void Main(string[] args)
{
Elem e = new Elem();
e.name[0] = "fsdfsdfsdf";
e.name[1] = "dad";
Console.WriteLine(e.name[0]);
Console.WriteLine(e.name[1]);
Console.ReadLine();
}
}
}

------解决方案--------------------
C# code
            Elem e = new Elem();
            string[] s = new string[2];
            s[0] = "fsdfsdfsdf";
            s[1] = "dad";
            e.name = s;
            Console.WriteLine(e.name[0]);
            Console.WriteLine(e.name[1]);
            Console.ReadLine();

------解决方案--------------------
3楼:
结构中不能有实例字段初始值设定项
------解决方案--------------------
setvalue
------解决方案--------------------
没有设置初始长度不能用e.name[0] 这样的写法
------解决方案--------------------
C# code

public int n=2;
public string [] name=new string[n];// 数组在初始化的时候规定存储空间也就是数组长度

------解决方案--------------------
Elem em;
em.name = new string[5];
em.name[0] = "3213213213";
------解决方案--------------------
动态的?那就改用ArrayList吧。。
------解决方案--------------------
探讨
C# codeElem e=newElem();string[] s=newstring[2];
s[0]="fsdfsdfsdf";
s[1]="dad";
e.name=s;
Console.WriteLine(e.name[0]);
Console.WriteLine(e.name[1]);
Console.ReadLine();

------解决方案--------------------
Elem e = new Elem();
e.name=new String[2];//必须先进行初始化,才能给其赋值啊。
e.name[0] = "fsdfsdfsdf";
e.name[1] = "dad";
Console.WriteLine(e.name[0]);
Console.WriteLine(e.name[1]);
Console.ReadLine();

------解决方案--------------------