簡體   English   中英

"如何在 Smalltalk 中找到所有可用的方法並按名稱搜索?"

[英]How to find all methods available in Smalltalk and search by name?

在 Smalltalk 中,有沒有辦法搜索(任何對象的)所有可用方法,比如包含單詞convert<\/code> (不區分大小寫的搜索),還包含單詞string<\/code> ? (方法名,不是源代碼)

"

在Smalltalk中,您可以直接訪問所有類,它們的方法和源代碼,因此您可以瀏覽它們。

菲羅

遍歷所有類,然后從每個類中選擇符合您需求的所有方法(或使用Finder工具)。

Object withAllSubclasses flatCollect: [ :cls |
    cls methods select: [ :method |
        (method selector includesSubstring: 'convert' caseSensitive: false) and: [
        (method selector includesSubstring: 'string' caseSensitive: false) ]
    ]
].

GNU Smalltalk

GST沒有那么好的API,但它也可以做到。

(Object withAllSubclasses collect: [ :cls |
    cls methodDictionary ifNotNil: [ :dict |
        dict values select: [ :method |
            (method selector asLowercase indexOfSubCollection: 'convert' asLowercase) > 0 and: [
            (method selector asLowercase indexOfSubCollection: 'string' asLowercase) > 0 ]
        ]
    ]
]) join

VisualWorks中

(也是Pharo和Squeak,還有ifNotNil:還有GNU Smalltalk)

大眾沒有#flatten ,所以它是明確實現的。 對於不區分大小寫的搜索#findSameAs:startingAt:wildcard:也可以使用。

(Object withAllSubclasses collect: [ :cls |
    cls methodDictionary values select: [ :method |
        (method selector asLowercase findString: 'convert' asLowercase startingAt: 1) > 0 and: [
        (method selector asLowercase findString: 'string' asLowercase startingAt: 1) > 0 ]
    ]
]) inject: #() into: [ :arr :each | arr, each ]

海豚

海豚似乎有不同的對象模型,請參閱下面的Leandro的答案

這可能不適用於所有的smalltalk方言,但它至少適用於吱吱聲和pharo(其他小方可能有類似的工具/類)

SystemNavigation default browseAllSelect:[:e |
(e selector includesSubstring:'convert' caseSensitive:false)
    and:[e selector includesSubstring:'string' caseSensitive:false]]

這更像是@Peter給出的答案的補充。

請注意,在某些方言(例如,Dolphin)中,消息#withAllSubclasses將僅收集類,而不是元類。 因此,@ Peter的答案中的枚舉應該以明確的方式添加所有元類。

例如,

selectors := OrderedCollection new.
Object withAllSubclasses do: [:class | | matching |
  matching := class selectors select: [:s |
    (s includesString: 'onvert') and: [s includesString: 'tring']].
  selectors addAll: matching.
  matching := class class selectors select: [:s |
    (s includesString: 'onvert') and: [s includesString: 'tring']].
  selectors addAll: matching].
^selectors

請注意,我已經刪除了'convert''string'的第一個字母,以便廉價地防止案例不匹配。

與我的代碼的另一個區別是它迭代了類的selectors而不是它的方法。

UPDATE

請注意,我使用了兩個枚舉,因為我們不能這樣做:

class selectors , class class selectors select: [:s |

原因是一個classselectors進入一個Set ,這些不理解#,

我們本可以做到:

all := class selectors addAll: class class selectors; yourself.
all selectors select: [:s |

等(注意使用#yourself

這是為上面的列表添加不同的風味。

@Smalltalk\/X<\/h2>
 Object withAllSubclasses flatCollect: [ :cls | cls methodDictionary values select: [ :method | (method selector includesSubstring: 'convert' caseSensitive: false) and: [ (method selector includesSubstring: 'string' caseSensitive: false) ] ] ].<\/code><\/pre>"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM