简体   繁体   中英

override default new operator for an array of a class C#

I am using pinvokes to call native code.

if I want to create an array of the native objects I currently do the following

public class MyClass() {
    // allocate a single myClass;
    public MyClass() {
        _myClass = myclass_create();
        _length = 1;
    }
    public MyClass(int numArgs) {
        //pInvoke call to create an array of myclass;
        _myClass = myclass_array_create(UIntPtr);
        _length = numArgs;
     }

     //access the indexed element of myclass
     public MyClass this[int index] {
         get {
             MyClass ret = new MyClass();
             ret._myClass = myclass_array_element(this._myClass, (UIntPtr)index);
             return ret;
         }
     }

     public int Length {
         get {
             return _length;
         }
     }

     public void foo(){
         //lots of other code
     }


     [DllImport(DLL_IMPORT_TARGET)]
     private static extern IntPtr myclass_create();
     [DllImport(DLL_IMPORT_TARGET)]
     private static extern IntPtr myclass_array_create(UIntPtr numArgs);
     [DllImport(DLL_IMPORT_TARGET)]
     private static extern IntPtr myclass_array_element(IntPtr args, UIntPtr index);
     // ... more dllimports here ...

     //pointer to native object
     IntPtr _myClass;
     int _length;
}

This is now used as follows:

// Create an array of 15 MyClass objects
MyClass myClass = new MyClass(15);
for( int i = 0; i < myClass.Length; ++i) {
    //run foo on each object in the array
    myClass[i].foo()
}

I have this working just find however it is a little unusual to call new for something that is an array with out doing an array new.

is there a way that I can override the new operator for this class so the typical use of the new operator can be used instead?

I would like the code to look like this

// Create an array of 15 MyClass objects
MyClass[] myClass = new MyClass[15];
for( int i = 0; i < myClass.Length; ++i) {
    //run foo on each object in the array
    myClass[i].foo()
} 

Is there a way to do this with my code?

No, you cannot in any way override the behavior of how an array is initialized. You need to either:

  1. Use a different type that wraps an array, as you showed in the question.

  2. Call a method on the array after creating it to add additional initialization (ie assign a bunch of values to each index).

  3. Create a new method that, when called, will create and then initialize the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM