0

I have tried many ways like Cast<CustomObject>, as Customobject and ToArray(Customobject) but nothing worked.

How can I add List or ArrayList via AddRange to a CustomObject[] Array?

Code is really difficult. But if you have some time you can get the complete source of the destination list from here: http://www.codeproject.com/Articles/4012/C-List-View-v1-3?msg=3844172#xx3844172xx

This is a Custom Listview I activated a combobox for the second column, so I can select diferrent values for a cell. But before this, I have to add something to select. This is the hole problem.

Update: Firstly, thanks for the help ! Secondly, Found a solution in the comments from the website with the source. Had to add some code and changed the destination custom array to a List


If your current compiler doesn't yet support C++11, you can initialize the vector contents using standard algorithms and functors:

class sig
{
public:
    sig()
    {
        struct Functor
        {
            Functor() : value(0) {};
            int operator ()() { return value++; };
            int value;
        };
        std::generate(p_list, p_list + 4, Functor());
    }

    int p_list[4];
};

Previous snippet example here.

Yes, is kind of ugly (at least, it looks ugly for me) and doesn't do the work at compile time; but it does the work that you need in the constructor.

If you need some other kind of initialization (initialization with even/odd numbers, initialization with random values, start with anoter value, etc...) you only need to change the Functor, and this is the only advantage of this ugly approach.

4

5 に答える 5

6
list.Cast<CustomObject>().ToArray()

リスト内のものが実際にある限り機能しCustomObjectます。他のタイプの可能性がある場合は、OfType<CustomObject>()代わりに を使用できますCast。これにより、互換性のないタイプのものはすべて除外されます。

于 2012-09-13T12:33:17.723 に答える
1

objectsが実際に のインスタンスであると仮定して、CustomObjectLINQSelectメソッドを使用します。

objList.Select(o => o as CustomObject).ToArray();

それ以外の場合は、の配列を取得しますnull

于 2012-09-13T12:32:39.603 に答える
0

すべてのオブジェクトがタイプであるかどうかわからない場合は、CustomObject 試してください

var result = list.OfType<CustomObject>.ToArray();
于 2012-09-13T12:34:53.807 に答える
0

厳密に言えば、配列の長さは存続期間中一定であるため、配列に要素を追加することはできません。できることは 2 つあります。

新しいアレイを作成する

myArray = myTList.ToArray() // generic)
myArray = myArrayList.Cast<CustomObject>().ToArray() // cast, non-generic
myArray = myArrayList.OfType<CustomObject>().ToArray() // filter by type, non-generic

配列の要素を設定する

myArray[x] = myTList[y] // generic
myArray[x] = (CustomObject)myArrayList[y] // non-generic

可能な限りジェネリック コレクションを使用することをお勧めします。これらは追加の型安全性を提供します。変数をキャストobjectすると、ジェネリック型を使用してコンパイル時に検出できるランタイム エラーが発生します。

実際に既存のコレクションに要素を追加したい場合List<T> : IList<T>は、配列ではなく動的なコレクション タイプを使用してみLinkedList<T> : ICollection<T>Stack<T>くださいQueue<T>

于 2012-09-13T12:48:58.507 に答える
0

その場合、List<CustomObject>私たちは言いましょう

CustomObject[] coarr = list_of_customobject.ToArray();

ArrayList の場合

CustomObject[] coarr = arraylist.OfType<CustomObject>().ToArray();   
于 2012-09-13T12:33:08.720 に答える