powershell 7 初体验

支持枚举定义,类定义\类继承\接口继承,不支持接口定义\泛型类定义\泛型函数定义,但是作为shell脚本已经相当让人惊喜了, 基本逻辑可以直接套用C#语法格式

# enum_sample/main.ps1

enum TestEnum
{
    None = 0
    Hello = 1
    World = 2
}

[Flags()] enum TestFlags
{
    None = 0
    Read = 1
    Write = 2
}

# 声明的时候加类型就会有类型检查
[TestEnum] $a = [TestEnum]::Hello;
# 或者 Write-Output $a
[System.Console]::WriteLine($a);
[System.Console]::WriteLine($a -eq 1);
[System.Console]::WriteLine("===");
[TestFlags] $b = [TestFlags]::Read + [TestFlags]::Write;
[System.Console]::WriteLine($b);
[System.Console]::WriteLine($b.HasFlag([TestFlags]::Read));

输出结果

Hello
True
===
Read, Write
True
# class_sample/TestClass.psm1

class TestClass
{
    [int] $id = 0;
    [string] $name = "";

    TestClass([int] $id, [string] $name)
    {
        $this.id = $id;
        $this.name = $name;
    }

    [string] ToString()
    {
        return [string]::Format("id: {0}, name: {1}", $this.id, $this.name);
    }
}
# class_sample/main.ps1

# 使用另一个文件定义的类, 注意这里要写相对于文件的相对路径
Using module "./TestClass.psm1"

# 继承自定义类
class TestClassB : TestClass
{
    [string] $extraValue = "";

    TestClassB([int] $id, [string] $name, [string] $extraValue) : base($id, $name)
    {
        $this.extraValue = $extraValue;
    }

    #override
    [string] ToString()
    {
        return [string]::Format("id: {0}, name: {1}, extraValue: {2}", $this.id, $this.name, $this.extraValue);
    }

    [string] ToStringEx()
    {
        return [string]::Format("id: {0}, name: {1}, extraValue: {2}", $this.id, $this.name, $this.extraValue);
    }
}

# 继承系统类
class TestClassC : System.IComparable
{
    [int] $value;

    TestClassC([int] $value)
    {
        $this.value = $value;
    }

    [int] CompareTo([object] $other)
    {
        return $this.value - $other.value;
    }
}

[TestClass] $a = [TestClass]::new(123, "tom");
[System.Console]::WriteLine($a.ToString());

[TestClass] $b = [TestClassB]::new(123, "jerry", "mouse")
[System.Console]::WriteLine($b.ToString());
# 这里不转类型也行, 有点可惜
# [System.Console]::WriteLine($b.ToStringEx());
[System.Console]::WriteLine(([TestClassB])$b.ToStringEx());

[TestClassC] $c1 = [TestClassC]::new(1)
[TestClassC] $c2 = [TestClassC]::new(2)
[System.Console]::WriteLine($c1 -gt $c2);

输出结果

id: 123, name: tom
id: 123, name: jerry, extraValue: mouse
id: 123, name: jerry, extraValue: mouse
False
posted @   lunoctis  阅读(154)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示