- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
检查类是否使用特定特征的正确方法是什么?
最佳答案
虽然没有什么能阻止您使用方法来确定类是否使用特征,但推荐的方法是将特征与接口(interface)配对。所以你有:
class Foo implements MyInterface
{
use MyTrait;
}
其中 MyTrait
是 MyInterface
的实现。
然后你检查接口(interface)而不是像这样的特征:
if ($foo instanceof MyInterface) {
...
}
你也可以输入提示,这是你不能用特征做的:
function bar(MyInterface $foo) {
...
}
如果您绝对需要知道某个类是否使用了某个 trait 或实现,您只需向接口(interface)添加另一个方法,该方法会根据实现返回不同的值。
关于特征的 PHP instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36515677/
对于以下条件: if (a != null && a instanceof A) 或 if (a instanceof A) 首先检查 null 是否有任何优势(例如,性能方面)?两个条件的结果应该相
我正在编写一个方法,如果异常是 *someClass* 的实例,它将返回 true。但是我无法导入其中一个类,因为它在另一个模块中。我无法将该模块添加到项目中,所以我想,我不能使用 instanceo
这个问题在这里已经有了答案: The difference between "instanceof List" and 'o instanceof List" (2 个答案) 关闭 7 年前。 我知
多年来,我尽量避免使用 instanceof。在适用的情况下使用多态性或访问者模式。我想它只是在某些情况下简化了维护......还有其他需要注意的缺点吗? 但是我确实在 Java 库中到处看到它,所以
我没有看到以下任何区别: Object o = new LinkedList(); System.out.println(o instanceof List); System.
我正在像这样扩展对象: Object.prototype.is_a = function (x) { return this instanceof x; } 一切正常 "foo".is_a(Str
我在 NetBeans 中编码如下: public class Grafo { class Par { int a, b; Par(int a, int
我已经动态创建了布局。它有一些编辑文本、 TextView 、微调器等。 之后,我必须获取我介绍的关于这些 View 的信息。 所以我在做这样的事情 for(int i=0;i <= childs;i
等等!我知道还有其他非常相似的问题,但(也许是我)我需要回答其中的特定部分。 我知道可以说 Object.prototype 位于委托(delegate)链的最顶端。但是,在 Function 存在以
MooTools 有自己的instanceOf(instance, Type) 函数。 我只能假设它做了一些与 Javascript 的原生 instanceof 运算符不同的事情,但我似乎无法弄清楚
获取UTXO的方法 getUtoxs(address){ var options; if(Global.btc.network === "testnet"){ options = {
为什么在 JavaScript 中,Object instanceof Function 和 Function instanceof Object 都返回 true? 我在 Safari WebIns
为什么在 JavaScript 中 Object instanceof Function 和 Function instanceof Object 都返回 true? 我在 Safari WebIns
首先,我制作了一个“游戏渲染器”。 我的问题是,当我需要绘制当前元素时:我需要知道它是矩形、圆形还是图像等。 我的类(矩形、圆形...)是从图形扩展而来的。 public class Rectangl
想象一下,我想编写一个名为 isInstanceof 的无用方法,它返回一个 boolean。 我在想。但我不出去。 instanceof 必须像这样使用: [object] instanceof [
我有两个继承自 Player 的类:SimplePlayer 和 InterleavedPlayer。 B 类有这些方法:setPlayer(SimplePlayer player) 和 setPla
我在尝试使用以下内容时遇到了意外行为: $object instanceof $class 1/如 in the official doc. 所述,PHP 'instanceof' 关键字和命名空间可
可以在 angularjs 中使用 typeof 吗? 我有一个 ngrepeat 循环遍历我的数据,应该检查数据是字符串还是对象。 {{angular.isObject(text) &&
例如,我有 Currency 和处理 Currency 各种实现的 Exchange。我想对窗帘货币有额外的汇率,我这样做 interface Currency { double rate();} i
我有以下代码: abstract class BaseToken {} class OpenParen extends BaseToken { public static assert(t:
我是一名优秀的程序员,十分优秀!