[英]What is the difference of calling methods between in derived function and with new key word in Solidity?
I noticed there are two methods to call the contract's functions in Solidity as follow.我注意到有两种方法可以调用 Solidity 中的合约函数,如下所示。
// Base contract
contract A {
function X() public pure returns (string memory s) {
s = 'Base contract function X';
}
}
// Inherited contract
contract B is A {
function Y() public pure returns (string memory s) {
s = string.concat(X(), ' + Inherited contract function Y');
}
}
// Contract with new key word
contract C {
A contractA = new A();
function Z() public view returns (string memory s2) {
s = string.concat(contractA.X(), ' + Contract C function Z');
}
}
I don't understand the difference between contract B and C, especially in what case should I use inheritance, or new key word to call a function?我不明白合同B和C的区别,特别是在什么情况下我应该使用inheritance,或者新的关键字来调用function?
In the inherited contract, contract B includes contract A and it doesn't deploy an external contract.继承合约中,合约B包含合约A,不部署外部合约。 It means it calls the X() function of itself.
这意味着它调用自己的 X() function。 In the second case with the new keyword, it deploys the contract A and calls the X() function of the external contract A
第二种情况,new关键字,部署合约A,调用外部合约A的X() function
What you shared in the post is a good example of the inheritance
and composition
.您在帖子中分享的是
inheritance
和composition
的一个很好的例子。 When to use each of this design decisions is a general engineering question and doesn't relate to solidity.何时使用每个设计决策是一个通用的工程问题,与可靠性无关。 Here is one of discussions of this topic.
这是关于该主题的讨论之一。
new
keyword is used to create a new instance of the class. Although I am not sure it is possible to instantiate contract in solidity in a such way. new
关键字用于创建 class 的新实例。虽然我不确定是否有可能以这种方式在 solidity 中实例化合约。 I did this by passing an address of the contract:我通过传递合同地址来做到这一点:
class Chain {
Token _token;
constructor(address _tokenAddress) {
_token = Token(_tokenAddress);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.