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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C#中[]的幾種用法示例代碼_C#教程

作者:迪迦???奧特曼 ? 更新時(shí)間: 2023-03-21 編程語言

一、導(dǎo)入外部DLL函數(shù)

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

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

extern 作用:標(biāo)識這個(gè)變量或者函數(shù)定義在其他文件 ,提示編譯器遇到此變量的時(shí),在其他模塊里尋找,這里是在提供的動(dòng)態(tài)庫里找
示列代碼:

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);
        }
    }
}

二、結(jié)構(gòu)體時(shí)表明屬性

[StructLayout(LayoutKind.Sequential) ][StructLayout(LayoutKind.Explicit)] ,首先介紹一下 結(jié)構(gòu)體和類的區(qū)別 :類是按引用傳遞 結(jié)構(gòu)體是按值傳遞

進(jìn)入正題:

結(jié)構(gòu)體是由若干成員組成的.布局有兩種

1.Sequential,順序布局,比如

struct S1{
  int a;
  int b;
}

那么默認(rèn)情況下在內(nèi)存里是先排a,再排b

也就是如果能取到a的地址,和b的地址,則相差一個(gè)int類型的長度,4字節(jié)

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

這樣和上一個(gè)是一樣的.因?yàn)槟J(rèn)的內(nèi)存排列就是Sequential,也就是按成員的先后順序排列.

2.Explicit,精確布局

需要用FieldOffset()設(shè)置每個(gè)成員的位置

這樣就可以實(shí)現(xiàn)類似c的公用體的功能

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

這樣a和b在內(nèi)存中地址相同

總結(jié)

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

欄目分類
最近更新