首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell GetType

Powershell GetType
EN

Stack Overflow用户
提问于 2021-02-14 19:55:26
回答 2查看 487关注 0票数 2

我想检查一下是否存在某种类型。例如:

代码语言:javascript
复制
Add-Type -TypeDefinition '
public class Test{
    public static int aaa(){
        return 1;
    }
}'

[test]::aaa() # 1

[type]::GetType('test') # empty

但是GetType()不适用于我的“test”类型。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-14 20:23:52

您可以测试类型是否已经存在于

代码语言:javascript
复制
if (-not ('Test' -as [type])) {
# or 
# if (-not ([System.Management.Automation.PSTypeName]'Test').Type) {
    Add-Type -TypeDefinition '
    public class Test{
        public static int aaa(){
            return 1;
        }
    }'
}

我不知道为什么[type]::GetType('test')不起作用,但是

代码语言:javascript
复制
("Test" -as [type])

是否工作并返回$null或

代码语言:javascript
复制
IsPublic IsSerial Name                                     BaseType                                                                                                               
-------- -------- ----                                     --------                                                                                                               
True     False    Test                                     System.Object
票数 3
EN

Stack Overflow用户

发布于 2021-02-16 15:14:27

补充西奥的有用答案,这无疑显示了最好的解决方案(-as [Type]),与为什么失败

  • System.Type.GetType() 只从加载自磁盘或保存到磁盘的程序集中查找类型--也就是说,从先前存在的程序集文件加载的类型或动态创建的程序集中的类型也(可选)持久化到磁盘。
  • 相反,当您在[Type]::GetType()中动态定义类型时,它们是在动态、内存中的程序集中创建的,这些程序集是而不是,因此E 229 PowerShell E 133看不到它们E 234。请注意,这同样适用于:
代码语言:javascript
复制
- Types created with [`Add-Type`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/add-type) `-TypeDefinition` or `-MemberDefinition`
代码语言:javascript
复制
- Types created with the (PSv5+) `class` and `enum` keywords, i.e. custom PowerShell classes and enumerations.

但是,[Type]::GetType()提供了重载功能,可以将自定义程序集-解析器功能连接到类型查找过程中,即在其他地方查找程序集中的类型。

这大概是PowerShell在幕后使用的(包括)在查找过程中只使用内存中的动态程序集的方法,它在以下上下文中起作用(一般情况下是不敏感的,比如PowerShell ):

  • 在最明显的形式中,在类型中,文字类型是 ([<typeName>]),因此您可以将您的Test类型称为[Test]
代码语言:javascript
复制
- Such type literals therefore also work with `-is`, the [type(-inheritance) / interface test operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Type_Operators), so you can test a given object for being of or deriving from the given type / implementing the given interface type.
代码语言:javascript
复制
- Caveat: If the type name inside `[...]` isn't recognized as a loaded or dynamically declared type, an _exception_ occurs, which surfaces as a _statement-terminating error_ in PowerShell.
代码语言:javascript
复制
- This approach tests if the string contains a type name that refers to a loaded type that can therefore be converted to a type-_information_ object.
- If so, such a type-information object is returned (the equivalent of `[Test]`, in your example); if not, `$null` is returned
- In a Boolean context such as an `if` conditional, a type-information object getting returned is implicitly `$true`, where as `$null` is implicitly `$false` - see the bottom section of [this answer](https://stackoverflow.com/a/53108138/45375) for the exact rules of implicit to-Boolean conversion), so the `-as [type]` approach is the most convenient way to test a type's presence.
  • 当您将[type]:转换为时,类型名称字符串转换为 [type] 'Test'
代码语言:javascript
复制
- Unlike the `-as` approach, this approach triggers an _exception_ that surfaces as a _statement-terminating error_ in PowerShell.
- The (more verbose and less efficient) equivalent of `if ('Test' -as [type]) ...` is

if ($(try { [type] 'Test' } catch { $null })) ...

关于名称空间的说明

  • 使用class enum enum创建的类型具有无命名空间组件E 2106,因此仅以它们自己的名称引用类型就足够了,如D 107
  • 通过Add-Type创建的类型
代码语言:javascript
复制
- via **`-TypeDefinition`** (arbitrary C# code):
代码语言:javascript
复制
    - Whether you need a namespace qualifier depends on whether you enclose the new type's declaration in a `namespace <identifier> { ... }` construct or not.
代码语言:javascript
复制
- via **`-MemberDefinition`** (C# code for declaring static methods, typically for [P/Invoke](https://en.wikipedia.org/wiki/Platform_Invocation_Services) calls):
代码语言:javascript
复制
    - You _do_ need a namespace qualifier to refer to the resulting type, namely either the one you've specified explicitly via the `-Namespace` parameter or the the implicitly used `Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes.WinApi` namespace.
代码语言:javascript
复制
    - You can bypass having to refer to the type by namespace-qualified name by using the `-PassThru` switch and saving the type-definition object in a variable, which allows you to call its static methods directly via that variable.
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66199510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档