
在PHP中,接口是一种定义了一组方法的抽象类。我们可以通过实现接口来保证类具有特定的行为。然而,有时候我们需要从对接口的引用中获取对具体类型的引用。这在某些情况下可能会导致一些困惑。所以,本文将向大家介绍如何从对接口的引用中获取对具体类型的引用。无论您是初学者还是有一定经验的开发者,本文都将对您有所帮助。接下来,让我们进入正题,一起探索这个问题的解决方案。
我试图了解 go 中的方法、接口和具体类型是如何工作的。
比如,这里。
我的代码为:
type i interface {mymethod(....)}
type a struct{i i....}
func (a *a) mymethod(....) {
}所以a实现了接口i。
在客户端代码中:
i := somefunction(....) // i is of type I i.MyMethod(....)
如何从 i 获取对 a 的引用?
一组方法签名存储在接口类型中。 接口中定义的方法的任何实现都可以存储为其值。
如果变量是使用接口类型定义的,可以访问接口中定义的方法以及与实现的类型关联的其他方法无法访问。
界面:
type i interface {
value() string
}
实施:
type a string
func(a a) value() string {
return string(a)
}
func (a a) type() string {
return reflect.typeof(a).name()
}
在客户端代码中:
// define a variable with the type of i.
var a i = a("a")
// method value() defined in the i interface can be
// called.
value := a.value()
// method type() can not be called, because it is not defined in the interface.
typ := a.type()
注意:如果使用指针接收器实现方法,如下所示。您需要将实现的指针分配给i。
实施:
type a string
func(a *a) value() string {
return string(a)
}
在客户端代码中:
a := A("a")
var i I = &a
以上就是如何从对接口的引用中获取对具体类型的引用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号