簡體   English   中英

PowerShell(新對象)C# 和結構

[英]PowerShell (New-Object) C# and Struct

我已經能夠讓以下代碼工作,並想了解更多關於 STRUCT 和 New-Object 的信息。

如果我在 CLASS (MyClass) 中移動 STRUCT (MyRect),我將如何引用它? 現在,它如下(在 CLASS 和同一級別之外)並且它是有效的。

$Rectangle = New-Object MyRECT
    

我曾嘗試將其移動到 CLASS 內,但它出錯了。 最有可能的 Struct 應該始終與 Class 處於同一級別,對吧? 無論如何,是否有適當的方法來聲明這一點?

$Rectangle = New-Object [MyClass]::MyRECT

如果您有什么想指出的,在實踐方面,請告訴我,比如下面兩種方法哪個更好用? 謝謝

clear-host

$code = 
@'
    using System;
    using System.Runtime.InteropServices;
    
    public class MyClass
    {
        [DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, out MyRECT lpRect);

        public static MyRECT Test3(int intHWND)
        {
            MyRECT TT = new MyRECT();
            GetWindowRect((System.IntPtr) intHWND, out TT);
            
            return TT;
        }
    }

    public struct MyRECT
    {
        public int      Left;        // x position of upper-left corner
        public int      Top;         // y position of upper-left corner
        public int      Right;       // x position of lower-right corner
        public int      Bottom;      // y position of lower-right corner
    }
'@
Add-Type -TypeDefinition $Code

[Int]$HWND = (Get-Process -ID 9768).MainWindowHandle
$HWND

$oTest3 = [MyClass]::Test3($HWND)
$oTest3.Left
$oTest3.Top
$oTest3.Right
$oTest3.Bottom

$Rectangle = New-Object MyRECT
$null = [MyClass]::GetWindowRect([IntPtr]$HWND,[ref]$Rectangle)

$Rectangle.Left
$Rectangle.Top
$Rectangle.Right
$Rectangle.Bottom

感謝 Jeroen Mostert

clear-host

$code = 
@'
    using System;
    using System.Runtime.InteropServices;
    
    public class MyClass
    {
        [DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, out MyRECT lpRect);

        public struct MyRECT
        {
            public int      Left;        // x position of upper-left corner
            public int      Top;         // y position of upper-left corner
            public int      Right;       // x position of lower-right corner
            public int      Bottom;      // y position of lower-right corner
        }

        public static MyRECT Test3(int intHWND)
        {
            MyRECT TT = new MyRECT();
            GetWindowRect((System.IntPtr) intHWND, out TT);
            
            return TT;
        }
    }

'@
Add-Type -TypeDefinition $Code

[Int]$HWND = (Get-Process -ID 9768).MainWindowHandle
$HWND

$oTest3 = [MyClass]::Test3($HWND)
$oTest3.Left
$oTest3.Top
$oTest3.Right
$oTest3.Bottom

$Rectangle = New-Object MyClass+MyRECT
$null = [MyClass]::GetWindowRect([IntPtr]$HWND,[ref]$Rectangle)

$Rectangle.Left
$Rectangle.Top
$Rectangle.Right
$Rectangle.Bottom

暫無
暫無

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

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