假设我有以下内容:
type T struct { Name string }
然后我创建了一个类型为T的var:
thing := T{"Hello World"}
然后我反映出类型:
t := reflect.TypeOf(thing) // main.T
然后我将t
传递给接受接口的方法,在那种方法中我是否有任何方式可以说接受的interface{}
属于main.T
类型我有那个字符串吗?
用例是我有一个适合类型的json字符串。我有一个这种类型的字符串(main.T
),我希望能够创建一个类型为main.t
的新变量,当我只知道字符串main.T
然后编组数据到那个新变量。
答案 0 :(得分:0)
Go运行时没有提供一种在给定类型名称的情况下创建值的方法,但这可以在应用程序中实现:
v := reflect.New(types[name]).Interface()
您可以使用以下命令创建名称的新值:
var types = map[string]func() interface{} {
"main.T": func() interface{} { return &T{} }
}
v := types[name]()
这假定名称是有效名称。您可能想要检查类型[name] == nil。
的情况您也可以不加思考地执行此操作:
public partial class MyGeneric<T> : IMyGeneric<T> where T : IEntity
{
public MyGeneric(string stuff)
{
moreStuff(stuff);
}
//.. other stuff
}