C#中[]的几种用法

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一、导入外部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在内存中地址相同

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6