Solidity

在沒有其他契約的吸氣劑的情況下獲取array.length?

  • March 29, 2021

有沒有辦法在沒有 getter 的情況下在其他合約中獲取數組的長度?

pragma solidity ^0.4.11;

contract MyContractA {
   uint[] public myArray;

   function MyContractA() {
       myArray.length = 1;
   }

}

contract MyContractB {

   function test() returns (uint ret) {
       address instanceAddress = new MyContractA();
       MyContractA instance = MyContractA(instanceAddress);
       // works:
       return instance.myArray(0); 
       //
       // doesn't work: 
       //
       //  TypeError: Member "length" not found or not visible after argument-dependent lookup in function (uint256) constant external returns (uint256)
       // return instance.myArray.length;

       // TypeError: Member "length" not found or not visible after argument-dependent lookup in function (uint256) constant external returns (uint256)
       // return instance.myArray.length();

       //   TypeError: Wrong argument count for function call: 0 arguments given but expected 1.
       //return instance.myArray().length;
   }
}

不,您需要提供一個函式,該函式將數組長度作為uint.

就像是

function getCount() public view returns(uint count) {
   return array.length;
}

這是一個很常見的要求。這些儲存模式可能會為您節省一些時間來了解如何在我們正在處理的約束範圍內做事:Solidity 是否存在解決良好且簡單的儲存模式?

希望能幫助到你。

引用自:https://ethereum.stackexchange.com/questions/20812