reflect如何获取返回的结构指针

时间:2017-12-02 16:00:27

标签: pointers go struct reflection

package main

import (
    "fmt"
    "reflect"
)

type Blog struct {
    Name string
}

func (blog *Blog) Test() (*Blog){
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    var o interface{} = &Blog{}
    v := reflect.ValueOf(o)
    m := v.MethodByName("Test")
    rets := m.Call([]reflect.Value{})
    fmt.Println(rets)
}

我得到了以下输出:

  • 这是测试方法
  • []

为什么没有博客结构以及如何获取博客名称的价值?

2 个答案:

答案 0 :(得分:3)

package main

import (
    "fmt"
    "reflect"
)

type Blog struct {
    Name string
}

func (blog *Blog) Test() *Blog {
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    rv := reflect.ValueOf(&Blog{})
    rm := rv.MethodByName("Test")

    results := rm.Call(nil)
    fmt.Printf("%#v\n", results)

    blogPointer := results[0]
    fmt.Printf("%#v\n", blogPointer)

    blogValue := blogPointer.Elem()
    fmt.Printf("%#v\n", blogValue)

    nameFieldValue := blogValue.FieldByName("Name")
    fmt.Printf("%#v\n", nameFieldValue)

    name := nameFieldValue.String()
    fmt.Println(name)
}

https://play.golang.org/p/iyUw-Sp97-

答案 1 :(得分:1)

首先我们调用接口返回的函数,然后我们可以使用Elem()方法调用它的值来调用指向接口的指针

String[] extensions = { "*.bmp", "*.png", "*.jpg", "*.jpeg", "*.tiff", "*.ico", "*.gif" };
List<String> images = new List<String>();
foreach (String ext in extensions)
{
    try
    {
        images = images.Concat(Directory.GetFiles(path, ext)).ToList();
    }
    catch { }
}
ObservableCollection<ImageBlock> ImageCollection = new ObservableCollection<ImageBlock>();
foreach (String img in images)
    this.ImageList.Items.Add(new ImageBlock(img, System.IO.Path.GetFileName(img)));