C#中[]的几种用法示例代码
作者:迪迦???奥特曼 时间:2022-03-20 05:50:46
一、导入外部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
标签:c#,[]
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringCloud远程服务调用实战笔记
2022-07-13 06:40:19
docker 的java编译环境构建详细介绍
2023-02-10 04:08:30
SpringCloud版本问题报错及解决方法
2023-01-29 23:19:46
![](https://img.aspxhome.com/file/2023/1/61561_0s.png)
Spring Boot 2.0.0 终于正式发布-重大修订版本
2021-08-12 08:25:51
利用Thumbnailator轻松实现图片缩放、旋转与加水印
2022-03-26 18:44:04
![](https://img.aspxhome.com/file/2023/0/78050_0s.jpg)
Java消息队列JMS实现原理解析
2023-05-14 04:02:04
![](https://img.aspxhome.com/file/2023/4/81354_0s.png)
JAVA Future类的使用详解
2023-11-04 22:51:20
![](https://img.aspxhome.com/file/2023/5/88515_0s.jpg)
Java使用Log4j记录日志的方法详解
2022-09-19 01:09:50
![](https://img.aspxhome.com/file/2023/6/78236_0s.png)
三种Java自定义DNS解析器方法与实践
2022-01-13 10:12:11
Java 微信公众号开发相关总结
2021-11-11 03:43:30
![](https://img.aspxhome.com/file/2023/8/88048_0s.png)
springmvc中下载中文文件名称为下划线的解决方案
2023-11-25 22:28:53
一起来学习C#的观察者模式
2022-04-02 13:43:15
![](https://img.aspxhome.com/file/2023/5/78115_0s.png)
解析Tars-Java客户端源码
2023-04-08 01:18:39
![](https://img.aspxhome.com/file/2023/7/89587_0s.jpg)
Unity3D Shader实现扫描显示效果
2023-03-16 22:51:39
![](https://img.aspxhome.com/file/2023/7/84467_0s.gif)
Java jvm中Code Cache案例详解
2022-02-04 17:00:53
Android中TextView显示插入的图片实现方法
2023-08-06 00:27:42
Android中资源文件用法简单示例
2023-09-24 22:29:04
如何使用Java调用Linux系统命令
2021-12-24 20:45:31
SpringBoot整合Mybatis实现CRUD
2022-01-10 09:26:45
![](https://img.aspxhome.com/file/2023/5/84765_0s.png)
Java如何实现压缩文件与解压缩zip文件
2022-01-28 09:14:00
![](https://img.aspxhome.com/file/2023/6/67496_0s.png)