0

これは、任意のクラスからアクセスできるリストにインスタンスを格納する一般的な方法ですか。これを達成するためのより良いテクニックはありますか?

class fish
{

string species = "Gold Fish";

int age = 1;

public static list<fish> Listholder = new list<fish>();

Listholder.add(this);

}
4

3 に答える 3

3

List<T>はスレッド セーフではないため、異なるスレッドから魚を追加/削除する場合は、ConcurrentBag<T>代わりに使用する必要があります。

例えば:

public class Fish
{
    public string Species { get; set; }
    public int Age { get; set; }

    private static System.Collections.Concurrent.ConcurrentBag<Fish> Aquarium = new System.Collections.Concurrent.ConcurrentBag<Fish>();

    static Fish()
    {
        var goldFish = new Fish { Age = 1, Species = "Gold Fish" };
        PutFishIntoAquarium(goldFish);
    }

    public static void PutFishIntoAquarium(Fish fish)
    {
        Aquarium.Add(fish);
    }

    public static void ClearAquarium()
    {
        Fish someFish;
        while (!Aquarium.IsEmpty)
        {
            TryTakeFishOutOfAquarium(out someFish);
        }
    }

    public static bool TryTakeFishOutOfAquarium(out Fish fish)
    {
        if (Aquarium.TryTake(out fish))
            return true;
        return false;
    }

    public static bool TryLookAtSomeFish(out Fish fish)
    {
        if (Aquarium.TryPeek(out fish))
            return true;
        return false;
    }

}
于 2013-08-15T20:54:55.807 に答える
0

あなたが取得しようとしているのは、グローバルにアクセス可能な魚のリストをどこかに保存する方法だと思います. つまり、他のすべてのクラスが魚を取得する魚の中央リポジトリを持つことです。

その場合は、サービス/リポジトリ パターンなど、これを行う他の方法があります。変更可能な public static フィールドを使用すると、テストと再利用が難しくなることに注意してください。

于 2013-08-15T20:49:57.093 に答える
-1

クラスにはプロパティがあります。

このクラスを使用すると、オブジェクトを作成できます。

class fish()
{
    Private String _Type;
    Private Int _Age;
    Private String _Species;

    Public Type
    {
        get _Type;
        set _Type = Value;
    }
    Public Age
    {
        get _Age;
        set _Age = Value;
    }
    Public Species
    {
        get _Species;
        set _Species = Value;
    }
    public new(string Type, Int Age, String Species)
    {
        this.Type = Type;
        this.Age = Age;
        this.Species = Species;
    }
}

//this is your new object.
Fish SunFish = New Fish("small", 9, "Sunfish");

オブジェクトを作成した後、オブジェクトのリストを作成できます

于 2013-08-15T20:53:40.210 に答える