简体   繁体   English

获取参数类型的参数

[英]Get parameters of a parametric type

Suppose I define a type like that 假设我定义了类似的类型

type Point{Tx, Ty} end

Then I create a variable of this type, for example, 然后我创建一个这种类型的变量,例如,

a = Point{Int64, :something}()

Now, I only know that I can get the type of a by typeof(a) . 现在,我只知道我能得到的类型, atypeof(a) That is, Point{Int64, :something} . 也就是说, Point{Int64, :something} But, what I need is just the parameters Tx and Ty . 但是,我需要的只是参数TxTy

Are there ways that I can get those parameters Tx and Ty ? 我有办法获得这些参数TxTy吗?

You can define a function as follows 您可以按如下方式定义函数

eltypes{Tx,Ty}(::Type{Point{Tx, Ty}}) = (Tx, Ty)
eltypes(p) = eltypes(typeof(p))

(here ::Type{Point{Tx, Ty}} matches an argument of type Point{Tx, Ty} ) and use it (此处::Type{Point{Tx, Ty}}匹配Point{Tx, Ty}类型的参数并使用它

julia> eltypes(Point{Int, Float64}())
(Int64,Float64)

This is a frequently used idiom, for example in Base there is the similar function 这是一种常用的习语,例如在Base中有类似的功能

eltype{T}(::Type{Set{T}}) = T
eltype(x) = eltype(typeof(x))

typeof(a) is a DataType which has many fields. typeof(a)是一个包含许多字段的DataType you can get those names via: 你可以通过以下方式获得这些

julia> fieldnames(DataType)
10-element Array{Symbol,1}:
 :name        
 :super       
 :parameters  
 :types       
 :instance    
 :size        
 :abstract    
 :mutable     
 :pointerfree 
 :ninitialized

so if you need those parameters, run 所以,如果您需要这些参数,请运行

julia> collect(typeof(a).parameters)
2-element Array{Any,1}:
 Int64     
 :something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM