目錄
21.性能優(yōu)化
22.動(dòng)態(tài)dynamic使用
23.中文亂碼
24.啟動(dòng)項(xiàng)目之前,執(zhí)行文件
25.深拷貝-反射實(shí)現(xiàn)
26.丟棄運(yùn)算符 _
27.winform程序使用管理員運(yùn)行
28.wpf程序使用管理員運(yùn)行
29.Windows7上運(yùn)行.net6程序報(bào)錯(cuò)
30.字符串轉(zhuǎn)化字節(jié)數(shù)組,字節(jié)數(shù)組換成字符串
31.共享內(nèi)存
32.Lazy用法?
33.性能優(yōu)化Freezable
34.DataTable中Select的問(wèn)題
35.使用Dumpify可視化數(shù)據(jù)結(jié)構(gòu)
36.winform和wpf版本自動(dòng)生成控制
37.C#遞歸,尋找子節(jié)點(diǎn)
21.性能優(yōu)化
1.檢查空字符串:使用string.Empty
2.更改類(lèi)型轉(zhuǎn)換:使用as
3.字符串比較法:Equals("abc")
4.for循環(huán):使用--i比++i效率高
5.繼承,能少用就少用,代碼簡(jiǎn)潔了,但是效率低
22.動(dòng)態(tài)dynamic使用
先定義
public class DynamicInputParams : DynamicObject
{
Dictionary<string, object> property = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
string name = binder.Name;
return property.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
property[binder.Name] = value;
return true;
}
}
使用
dynamic P = new DynamicInputParams();
P.Name = "張三";
P.Age = 22;
P.Sex = "女";
P.a = "a";
Console.WriteLine(P.Name);
//也可以添加到List集合
List<dynamic> List = new List<dynamic>();
List.Add(P);
foreach (var item in List)
{
Console.WriteLine(item.Name);
}
或者
dynamic retObject;
retObject = new { retcode = "0", retmsg = "成功", data = 1 };
23.中文亂碼
AppContext.SetSwitch("Switch.System.Windows.Controls.Text.UseAdornerForTextboxSelectionRendering", false);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
string[] strAll = await System.IO.File.ReadAllLinesAsync(filePath, Encoding.GetEncoding("gbk"));
24.啟動(dòng)項(xiàng)目之前,執(zhí)行文件
1.建立1.bat,demo是要關(guān)閉的進(jìn)程
taskkill /IM demo.exe /F
2.生成前事件命令行,注意目錄的路徑
powershell.exe -Command "Start-Process '$(SolutionDir)\1.bat' -Verb RunAs"
25.深拷貝-反射實(shí)現(xiàn)
還可以使用別的方式實(shí)現(xiàn)
// 利用反射實(shí)現(xiàn)深拷貝
#region MyRegion
public static T DeepCopyWithReflection<T>(T obj)
{
Type type = obj.GetType();
// 如果是字符串或值類(lèi)型則直接返回
if (obj is string || type.IsValueType) return obj;
// 如果是數(shù)組
if (type.IsArray)
{
Type elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));
var array = obj as Array;
Array copied = Array.CreateInstance(elementType, array.Length);
for (int i = 0; i < array.Length; i++)
{
copied.SetValue(DeepCopyWithReflection(array.GetValue(i)), i);
}
return (T)Convert.ChangeType(copied, obj.GetType());
}
object retval = Activator.CreateInstance(obj.GetType());
PropertyInfo[] properties = obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.Static);
foreach (var property in properties)
{
var propertyValue = property.GetValue(obj, null);
if (propertyValue == null)
continue;
property.SetValue(retval, DeepCopyWithReflection(propertyValue), null);
}
return (T)retval;
}
#endregion
26.丟棄運(yùn)算符 _
使用_,編譯器不會(huì)出現(xiàn)提示警告了
_ = Task.Run(() =>
{
});
27.winform程序使用管理員運(yùn)行
1.首先建立一個(gè)winform程序
2.增加app.manifest文件
3.修改代碼
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
4. 重新生成,查看生成目錄
會(huì)看到一個(gè)帶有盾牌的exe,就是已經(jīng)增加了管理員權(quán)限的程序
?
并且啟動(dòng)的時(shí)候,還會(huì)要求使用管理員運(yùn)行vs軟件
?注意:當(dāng)計(jì)算機(jī)登錄用戶已經(jīng)是管理員的話,那么exe就不會(huì)出現(xiàn)盾牌。即使把生成帶有盾牌的exe,復(fù)制過(guò)去,也不會(huì)帶有盾牌。
28.wpf程序使用管理員運(yùn)行
和winform差不多,只是項(xiàng)目的結(jié)構(gòu)不一樣
1.使用.net6創(chuàng)建一個(gè)wpf程序
2.?增加app.manifest文件
3.修改代碼
4. 重新生成,查看生成目錄
會(huì)看到一個(gè)帶有盾牌的exe,就是已經(jīng)增加了管理員權(quán)限的程序
29.Windows7上運(yùn)行.net6程序報(bào)錯(cuò)
報(bào)錯(cuò)KERNELBASE.dll問(wèn)題
此問(wèn)題是Windows7缺少了系統(tǒng)更新的文件,使用騰訊電腦管家,進(jìn)行更新即可,或者其他系統(tǒng)更新軟件。
30.字符串轉(zhuǎn)化字節(jié)數(shù)組,字節(jié)數(shù)組換成字符串
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
Encoding FromEcoding = Encoding.GetEncoding("UTF-8");
Encoding ToEcoding = Encoding.GetEncoding("gb2312");
byte[] FromBytes = FromEcoding.GetBytes("你好");
byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, FromBytes);
Encoding FromEcoding1 = Encoding.GetEncoding("gb2312");
Encoding ToEcoding1 = Encoding.GetEncoding("UTF-8");
byte[] Tobytes1 = Encoding.Convert(FromEcoding, ToEcoding, Tobytes);
string s = ToEcoding.GetString(Tobytes);
31.共享內(nèi)存
MemoryMappedFile,進(jìn)程之前共享一個(gè)文件。
string fileName = @"D:\1\1.txt";
using (var mmFile = MemoryMappedFile.CreateFromFile(fileName, FileMode.OpenOrCreate, "fileHandle", 1024 * 1024))
{
string valueToWrite = "123456789";
var myAccessor = mmFile.CreateViewAccessor();
myAccessor.WriteArray<byte>(0, Encoding.ASCII.GetBytes(valueToWrite), 0, valueToWrite.Length);
var readout = new byte[valueToWrite.Length];
myAccessor.ReadArray<byte>(0, readout, 0, readout.Length);
var finalValue = Encoding.ASCII.GetString(readout);
MessageBox.Show(finalValue);
}
32.Lazy用法?
Lazy是一種延遲加載技術(shù),就是比較懶,只有在需要的時(shí)候,才會(huì)去執(zhí)行第一次,但是只要執(zhí)行第一次以后,就不需要再次執(zhí)行了,提高了性能。
// 創(chuàng)建一個(gè)Lazy實(shí)例,傳入一個(gè)委托,該委托將在第一次訪問(wèn)時(shí)執(zhí)行 //順序2,只調(diào)用一次,以后不要調(diào)用了
Lazy<int> lazy = new Lazy<int>(() =>
{
Console.WriteLine("計(jì)算結(jié)果...");
return 42; // 模擬耗時(shí)操作
});
private void button_Click(object sender, RoutedEventArgs e)
{
// 訪問(wèn)Lazy實(shí)例的值,這將觸發(fā)委托的執(zhí)行
Console.WriteLine("第一次訪問(wèn): " + lazy.Value); //順序1
// 再次訪問(wèn)Lazy實(shí)例的值,這次將直接返回之前計(jì)算的結(jié)果,而不再執(zhí)行委托 //順序3
Console.WriteLine("第二次訪問(wèn): " + lazy.Value);
}
33.性能優(yōu)化Freezable
類(lèi)中繼承Freezable,可以讓類(lèi)進(jìn)行凍結(jié),從而提高性能,凍結(jié)后,不可以修改類(lèi)的屬性值,只能讀取。(非常底層的優(yōu)化,有些作用,但是意義不是很大)
34.DataTable中Select的問(wèn)題
當(dāng)使用Select選擇字段的值的時(shí)候,如果數(shù)據(jù)沒(méi)有更新,會(huì)出現(xiàn)少一條數(shù)據(jù)的情況。
比如,isCheck=‘1’,明明選擇了4條,但是在使用Select的時(shí)候,只有3條數(shù)據(jù)
此時(shí)就要在更改數(shù)據(jù)的地方,加上如下代碼。
dt.AcceptChanges();
35.使用Dumpify可視化數(shù)據(jù)結(jié)構(gòu)
1.安裝
2.代碼使用
var a = new
{
ID = "1",
Name = "故里2130",
Description = "故里2130"
};
a.Dump();
3.效果
多層數(shù)據(jù)嵌套也是可以的,幫助我們可視化復(fù)雜的數(shù)據(jù)結(jié)構(gòu)
36.winform和wpf版本自動(dòng)生成控制
可在.csproj文件中輸入下面的代碼
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<Platforms>AnyCPU;x64</Platforms>
<Version>5.1.$([System.DateTime]::UtcNow.ToString("yy")).$([System.DateTime]::UtcNow.ToString("MM"))</Version>
<FileVersion>6.1.$([System.DateTime]::Now.ToString("yy")).$([System.DateTime]::Now.ToString("MM"))</FileVersion>
</PropertyGroup>
</Project>
?可以換成net4.8版本
效果?
如果后綴出現(xiàn)字母的情況下,增加文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-571784.html
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
37.C#遞歸,尋找子節(jié)點(diǎn)
using System;
public class Node
{
public int Value { get; set; }
public Node Parent { get; set; }
public List<Node> Children { get; set; }
public Node(int value)
{
Value = value;
Children = new List<Node>();
}
}
public class Program
{
public static void Main()
{
// 創(chuàng)建父子嵌套類(lèi)的實(shí)例
Node root = new Node(1);
Node child1 = new Node(2);
Node child2 = new Node(3);
Node child11 = new Node(11);
Node child12 = new Node(12);
Node child13 = new Node(13);
Node child21 = new Node(21);
Node child22 = new Node(22);
Node child23 = new Node(23);
root.Children.Add(child1);
child1.Children.Add(child11);
child1.Children.Add(child12);
child1.Children.Add(child13);
root.Children.Add(child2);
child2.Children.Add(child21);
child2.Children.Add(child22);
child2.Children.Add(child23);
child1.Parent = root;
child2.Parent = root;
// 使用遞歸搜索給定值
int targetValue = 22;
Node result = FindValueRecursively(root, targetValue);
if (result != null)
{
Console.WriteLine("找到了值為 " + targetValue + " 的節(jié)點(diǎn)");
}
else
{
Console.WriteLine("未找到值為 " + targetValue + " 的節(jié)點(diǎn)");
}
}
public static Node FindValueRecursively(Node currentNode, int targetValue)
{
if (currentNode.Value == targetValue)
{
return currentNode;
}
foreach (Node child in currentNode.Children)
{
Node foundNode = FindValueRecursively(child, targetValue);
if (foundNode != null)
{
return foundNode;
}
}
return null; // 沒(méi)有找到目標(biāo)值
}
}
來(lái)源:記錄C#知識(shí)點(diǎn)(二)21-40_故里2130的博客-CSDN博客文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-571784.html
到了這里,關(guān)于記錄C#知識(shí)點(diǎn)(二)21-40的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!