日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

淺談C#中[]的幾種用法_C#教程

作者:迪迦???奧特曼 ? 更新時間: 2023-03-22 編程語言

一、導入外部DLL函數

[DllImport(“kernel32.dll”)]這叫引入kernel32.dll這個動態連接庫。這個動態連接庫里面包含了很多WindowsAPI函數,如果你想使用這面的函數,就需要這么引入。舉個例子:

[DllImport(“kernel32.dll”)]
private static extern void FunName(arg,[arg]);

extern 作用:標識這個變量或者函數定義在其他文件 ,提示編譯器遇到此變量的時,在其他模塊里尋找,這里是在提供的動態庫里找
示列代碼:

using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Windows.Help
{
    public partial class SystemInfo
    {
        [DllImport("kernel32")]
        public static extern void GetWindowsDirectory(StringBuilder WinDir, int count);
        [DllImport("kernel32")]
        public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
        public static void Main () {
            const int nChars = 128;
            StringBuilder Buff = new StringBuilder(nChars);
            GetWindowsDirectory(Buff, nChars);
            String t = "Windows路徑:" + Buff.ToString();
            System.Console.WriteLine(t);
        }
    }
}

在這里插入圖片描述

二、結構體時表明屬性

[StructLayout(LayoutKind.Sequential) ][StructLayout(LayoutKind.Explicit)] ,首先介紹一下 結構體和類的區別 :類是按引用傳遞 結構體是按值傳遞
進入正題:

結構體是由若干成員組成的.布局有兩種
1.Sequential,順序布局,比如

struct S1{
  int a;
  int b;
}

那么默認情況下在內存里是先排a,再排b
也就是如果能取到a的地址,和b的地址,則相差一個int類型的長度,4字節

[StructLayout(LayoutKind.Sequential)] 
struct S1
{
  int a;
  int b;
}

這樣和上一個是一樣的.因為默認的內存排列就是Sequential,也就是按成員的先后順序排列.
2.Explicit,精確布局
需要用FieldOffset()設置每個成員的位置
這樣就可以實現類似c的公用體的功能

[StructLayout(LayoutKind.Explicit)] 
struct S1
{
  [FieldOffset(0)]
  int a;
  [FieldOffset(0)]
  int b;
}

這樣a和b在內存中地址相同

原文鏈接:https://blog.csdn.net/qwq1503/article/details/128767923

欄目分類
最近更新