Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 使用反射调用方法并返回值_Oop_Reflection_Methods_Go - Fatal编程技术网

Oop 使用反射调用方法并返回值

Oop 使用反射调用方法并返回值,oop,reflection,methods,go,Oop,Reflection,Methods,Go,以关于的问题为出发点,我想按名称调用一个方法,并实际处理该值 package main import "fmt" import "reflect" type T struct{} func (t *T) Foo() { fmt.Println("foo") } type MyStruct struct { id int } type Person struct { Name string Age int } func (t *T) Bar(ms *M

以关于的问题为出发点,我想按名称调用一个方法,并实际处理该值

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) Foo() {
    fmt.Println("foo")
}

type MyStruct struct {
    id int
}

type Person struct {
    Name string
    Age  int
}

func (t *T) Bar(ms *MyStruct, p *Person) int {
    return p.Age

}

func main() {
    var t *T
    reflect.ValueOf(t).MethodByName("Foo").Call([]reflect.Value{})
    var ans int
    ans = reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value{reflect.ValueOf(&MyStruct{15}), reflect.    ValueOf(&Person{"Dexter", 15})})
}

但是,我得到以下错误:

prog.go:30: cannot use reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value literal) (type []reflect.Value) as type int in assignment
 [process exited with non-zero status] 

我应该做些什么来实际返回一个值?我尝试使用类型转换并将其设置为
int
,但编译器说它不能
[]反射.Value
调用
返回
[]反射.Value
,这是一个片段。为了进行类型转换,需要从切片中获取元素。一旦您有了一个
reflect.Value
实例,您就可以调用
Int()
来获取作为int64的值

var ans int64
ans = reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value{
    reflect.ValueOf(&MyStruct{15}), 
    reflect.ValueOf(&Person{"Dexter", 15})})[0].Int()
fmt.Println(ans)