標籤:

在C#的ArrayList中的對象可以是結構體嗎?如果可以,怎麼使用比較簡便?補充:結構體包含多個欄位。

PS:如果ArrayList中的對象包含多個欄位,如何使用其中某一個對象的某一個欄位? 這裡暫且不談與List&相比的效率問題。


可以,不推薦。

當成object 用會產生裝箱拆箱,影響性能,有泛型的list〈T〉


介紹一本書:CLR via C# 4th Edition,看Section 2。


答案是:可以。

使用的時候,如果只是取這個結構體,那麼和其他任意類型的對象一樣,通過Index訪問就可以了。但在取到這個結構體之後還需要進行拆箱,才能訪問結構體內的其他欄位。

我有一個笨辦法,打開IDE,然後寫一段代碼試一下,你就知道了。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Collections;

namespace ConsoleTest
{
internal static class Program
{
public static void Main()
{
int myInt = 0;
ArrayList al = new ArrayList();
TestStruct myFirstStruct = new TestStruct(1, "a");
al.Add(myFirstStruct);
TestStruct mySecondStruct = (TestStruct)al[0];
myInt = mySecondStruct.intA;
Console.WriteLine(al[0]);
Console.WriteLine(myInt);
Console.ReadKey();
}
}

public struct TestStruct
{
int intA;
string str;

public testStruct(int a, string s)
{
intA = a;
str = s;
}

public override string ToString()
{
return str + "s value is:" + intA;
}
}
}

我還有一個建議:多寫,多想,多搜索,不到萬不得已,別問。

再補充一下,要學會活用文檔。


不推薦這樣做。

可以使用泛型,成本更低效率更高。


自己回答一下。

可以使用多欄位的結構體。也可以使用其中某一個對象的某一個欄位。

但是,不可以直接使用。

使用方法:

Object[] myStandardArray = myArrayList.ToArray();

myStandardArray你就可以想怎麼用怎麼用了。


作為新手,我推薦你就這樣使用,怎麼簡單怎麼來,先實現功能應付工作差事再說

至於困難和問題,先不要想這麼多,等你真正遇到問題再來問,有一大大堆的大牛等著你後面的問題搶著回答。


推薦閱讀:

Unity3D 5.3 新版AssetBundle使用方案及策略
從遊戲腳本語言說起,剖析Mono搭建的腳本基礎
Visual Studio 開發體驗究竟牛到什麼程度?真的只是拖拖控制項就能完成中小型項目開發?
【譯】介紹 .NET Standard
妥協與取捨,解構C#中的小數運算

TAG:C# | 泛型Generic |