C#学习笔记

最近有朋友出于兴趣爱好,想对一个软件做一些修改,这个软件是C#写的,而这位朋友不懂编程,因此自己折腾的时候比较痛苦,就来问我。我也没用过C#,因此自己去看了下C#的语法,准备从理清楚代码逻辑上给他一些帮助。

基本概念

包管理工具

创建Web应用

可以基于WebWindow来实现:

https://github.com/SteveSandersonMS/WebWindow/

https://blog.stevensanderson.com/2019/11/18/2019-11-18-webwindow-a-cross-platform-webview-for-dotnet-core/

网页如何与系统通信,以调用系统API呢?

As a slightly more advanced option, you can configure the WebWindow to handle a custom scheme such as myapp:// and specify a delegate (callback) that returns arbitrary content for each URL within that scheme. Example here and here.

Once your web content is running, the low-level way to communicate between JavaScript and .NET is using the APIs window.external.sendMessage/receiveMessage in JS (example) and webWindowInstance.SendMessage and webWindowInstance.OnWebMessageReceived in .NET - (example). However if you’re building a Blazor app, you don’t need to use these low-level APIs and can use Blazor’s regular JS interop feature instead.

线程

1
2
3
4
5
6
if (Started || EnvirThread != null) return;

EnvirThread = new Thread(EnvirLoop) { IsBackground = true };
// 测试:给此线程最高优先级
EnvirThread.Priority = ThreadPriority.Highest;
EnvirThread.Start();

一些小知识

如何查看老项目的C#版本是多少?

找到项目下的.csproj文件,查看里面的Project ToolsVersion,就是版本号了。

如何降级.NetFramework版本

先卸载,然后安装开发工具包即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
Random random = new Random();
/* 我的第一个 C# 程序*/
Console.WriteLine(random.Next(1));
Console.ReadKey();
}
}
}

如何加载动态链接库

在项目的工程文件(*.csproj)中进行配置:

1
2
3
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>

我之前遇到一个问题,是Microsoft.DirectX.Direct3D.dll这个库没有。

中国式四舍五入

1
(int)Math.Round(((350 + 120) / 100f), MidpointRounding.AwayFromZero);

https://www.cnblogs.com/fanyong/archive/2013/05/30/chinese_round.html

调用Math.Round就可以了,记得加MidpointRounding.AwayFromZero这个参数,不然是采用默认的银行家算法,和我们中国传统理解的四舍五入会有差异。