程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 10個C#法式員常常用到的適用代碼片斷

10個C#法式員常常用到的適用代碼片斷

編輯:C#入門知識

10個C#法式員常常用到的適用代碼片斷。本站提示廣大學習愛好者:(10個C#法式員常常用到的適用代碼片斷)文章只能為提供參考,不一定能成為您想要的結果。以下是10個C#法式員常常用到的適用代碼片斷正文


1 讀取操作體系和CLR的版本

OperatingSystem os = System.Environment.OSVersion; 
Console.WriteLine(“Platform: {0}”, os.Platform); 
Console.WriteLine(“Service Pack: {0}”, os.ServicePack); 
Console.WriteLine(“Version: {0}”, os.Version); 
Console.WriteLine(“VersionString: {0}”, os.VersionString); 
Console.WriteLine(“CLR Version: {0}”, System.Environment.Version); 

在我的Windows 7體系中,輸入以下信息

Platform: Win32NT
Service Pack:
Version: 6.1.7600.0
VersionString: Microsoft Windows NT 6.1.7600.0
CLR Version: 4.0.21006.1
2 讀取CPU數目,內存容量

可以經由過程Windows Management Instrumentation (WMI)供給的接口讀取所須要的信息。

private static UInt32 CountPhysicalProcessors() 
{ 
   ManagementObjectSearcher objects = new ManagementObjectSearcher( 
    “SELECT * FROM Win32_ComputerSystem”); 
   ManagementObjectCollection coll = objects.Get(); 
   foreach(ManagementObject obj in coll) 
  { 
    return (UInt32)obj[“NumberOfProcessors”]; 
  } 
  return 0; 
} 
private static UInt64 CountPhysicalMemory() 
{ 
  ManagementObjectSearcher objects =new ManagementObjectSearcher( 
   “SELECT * FROM Win32_PhysicalMemory”); 
  ManagementObjectCollection coll = objects.Get(); 
  UInt64 total = 0; 
  foreach (ManagementObject obj in coll) 
  { 
    total += (UInt64)obj[“Capacity”]; 
  } 
  return total; 
} 

請添加對法式集System.Management的援用,確保代碼可以准確編譯。

Console.WriteLine(“Machine: {0}”, Environment.MachineName); 
Console.WriteLine(“# of processors (logical): {0}”, Environment.ProcessorCount); 
Console.WriteLine(“# of processors (physical): {0}” CountPhysicalProcessors()); 
Console.WriteLine(“RAM installed: {0:N0} bytes”, CountPhysicalMemory()); 
Console.WriteLine(“Is OS 64-bit? {0}”,  Environment.Is64BitOperatingSystem); 
Console.WriteLine(“Is process 64-bit? {0}”, Environment.Is64BitProcess); 
Console.WriteLine(“Little-endian: {0}”, BitConverter.IsLittleEndian); 
foreach (Screen screen in System.Windows.Forms.Screen.AllScreens) 
{ 
   Console.WriteLine(“Screen {0}”, screen.DeviceName); 
   Console.WriteLine(“\tPrimary {0}”, screen.Primary); 
   Console.WriteLine(“\tBounds: {0}”, screen.Bounds); 
   Console.WriteLine(“\tWorking Area: {0}”,screen.WorkingArea); 
   Console.WriteLine(“\tBitsPerPixel: {0}”,screen.BitsPerPixel); 
} 

3 讀取注冊表鍵值對

using (RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@”Software\Microsoft\Windows\CurrentVersion\Run”)) 
{ 
  foreach (string valueName in keyRun.GetValueNames()) 
  { 
   Console.WriteLine(“Name: {0}\tValue: {1}”, valueName, keyRun.GetValue(valueName)); 
  } 
} 

請添加定名空間Microsoft.Win32,以確保下面的代碼可以編譯。

4 啟動,停滯Windows辦事

這項API供給的適用功效經常用來治理運用法式中的辦事,而不用到掌握面板的治理辦事中停止操作。

ServiceController controller = new ServiceController(“e-M-POWER”);   
controller.Start();   
if (controller.CanPauseAndContinue)   
{   
  controller.Pause();   
  controller.Continue();   
}   
controller.Stop(); 

.net供給的API中,可以完成一句話裝置與卸載辦事

if (args[0] == "/i") 
{ 
    ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); 
} 
else if (args[0] == "/u") 
{ 
  ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); 
} 

如代碼所示,給運用法式傳入i或u參數,以表現是卸載或是裝置法式。

5 驗證法式能否有strong name (P/Invoke)

好比在法式中,為了驗證法式集能否有簽名,可挪用以下辦法

[DllImport("mscoree.dll", CharSet=CharSet.Unicode)] 
static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool pfWasVerified); 
 
bool notForced = false; 
bool verified = StrongNameSignatureVerificationEx(assembly, false, ref notForced); 
Console.WriteLine("Verified: {0}\nForced: {1}", verified, !notForced); 

這個功效經常使用在軟件掩護辦法,可用來驗證簽名的組件。即便你的簽名被人去失落,或是一切法式集的簽名都被去除,只需法式中有這一項挪用代碼,則可以停滯法式運轉。

6 呼應體系設置裝備擺設項的變革

好比我們鎖定體系後,假如QQ沒有加入,則它會顯示了勞碌狀況。

請添加定名空間Microsoft.Win32,然後對注冊上面的事宜。

. DisplaySettingsChanged (包括Changing) 顯示設置

. InstalledFontsChanged 字體變更

. PaletteChanged

. PowerModeChanged 電源狀況

. SessionEnded (用戶正在登出或是會話停止)

. SessionSwitch (變革以後用戶)

. TimeChanged 時光轉變

. UserPreferenceChanged (用戶偏號 包括Changing)

我們的ERP體系,會監測體系時光能否轉變,假如將時光調劑後ERP允許文件以外的規模,會招致ERP軟件弗成用。

7 應用Windows7的新特征

Windows7體系引入一些新特征,好比翻開文件對話框,狀況欄可顯示以後義務的進度。

Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog ofd = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog(); 
ofd.AddToMostRecentlyUsedList = true; 
ofd.IsFolderPicker = true; 
ofd.AllowNonFileSystemItems = true; 
ofd.ShowDialog(); 

用如許的辦法翻開對話框,與BCL自帶類庫中的OpenFileDialog功效更多一些。不外只限於Windows 7體系中,所以要挪用這段代碼,還要檢討操作體系的版本要年夜於6,而且添加對法式集Windows API Code Pack for Microsoft®.NET Framework的援用。

8 檢討法式對內存的消費

用上面的辦法,可以檢討.NET給法式分派的內存數目

long available = GC.GetTotalMemory(false); 
Console.WriteLine(“Before allocations: {0:N0}”, available); 
int allocSize = 40000000; 
byte[] bigArray = new byte[allocSize]; 
available = GC.GetTotalMemory(false); 
Console.WriteLine(“After allocations: {0:N0}”, available); 

在我的體系中,它運轉的成果以下所示

Before allocations: 651,064
After allocations: 40,690,080

應用上面的辦法,可以檢討以後運用法式占用的內存

Process proc = Process.GetCurrentProcess(); 
Console.WriteLine(“Process Info: “+Environment.NewLine+ 
“Private Memory Size: {0:N0}”+Environment.NewLine + 
“Virtual Memory Size: {1:N0}” + Environment.NewLine + 
“Working Set Size: {2:N0}” + Environment.NewLine + 
“Paged Memory Size: {3:N0}” + Environment.NewLine + 
“Paged System Memory Size: {4:N0}” + Environment.NewLine + 
 “Non-paged System Memory Size: {5:N0}” + Environment.NewLine, 
proc.PrivateMemorySize64,  proc.VirtualMemorySize64, proc.WorkingSet64, proc.PagedMemorySize64, proc.PagedSystemMemorySize64, proc.NonpagedSystemMemorySize64 ); 

9 應用記秒表檢討法式運轉時光

假如你擔心某些代碼異常消耗時光,可以用StopWatch來檢討這段代碼消費的時光,以下面的代碼所示

System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); 
timer.Start(); 
Decimal total = 0; 
int limit = 1000000; 
for (int i = 0; i < limit; ++i) 
{ 
   total = total + (Decimal)Math.Sqrt(i); 
} 
timer.Stop(); 
Console.WriteLine(“Sum of sqrts: {0}”,total); 
Console.WriteLine(“Elapsed milliseconds: {0}”, 
timer.ElapsedMilliseconds); 
Console.WriteLine(“Elapsed time: {0}”, timer.Elapsed); 

如今曾經有專門的對象來檢測法式的運轉時光,可以細化到每一個辦法,好比dotNetPerformance軟件。

以下面的代碼為例子,您須要直接修正源代碼,假如是用來測試法式,則有些不便利。請參考上面的例子。

class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable 
{ 
  public AutoStopwatch() 
  { 
    Start(); 
  } 
  public void Dispose() 
  { 
    Stop(); 
    Console.WriteLine(“Elapsed: {0}”, this.Elapsed); 
  } 
} 

借助於using語法,像上面的代碼所示,可以檢討一段代碼的運轉時光,並打印在掌握台上。

using (new AutoStopwatch()) 
{ 
  Decimal total2 = 0; 
  int limit2 = 1000000; 
  for (int i = 0; i < limit2; ++i) 
  { 
    total2 = total2 + (Decimal)Math.Sqrt(i); 
  } 
} 

10 應用光標

當法式正在後台運轉保留或是冊除操作時,應該將光標狀況修正為勞碌。可以使用上面的技能。

class AutoWaitCursor : IDisposable 
{ 
private Control _target; 
private Cursor _prevCursor = Cursors.Default; 
public AutoWaitCursor(Control control) 
{ 
  if (control == null) 
  { 
   throw new ArgumentNullException(“control”); 
  } 
  _target = control; 
  _prevCursor = _target.Cursor; 
  _target.Cursor = Cursors.WaitCursor; 
} 
public void Dispose() 
{ 
  _target.Cursor = _prevCursor; 
} 
} 

用法以下所示,這個寫法,是為了預感到法式能夠會拋出異常

using (new AutoWaitCursor(this)) 
{ 
... 
throw new Exception(); 
} 

如代碼所示,即便拋出異常,光標也能夠恢復到之間的狀況。

C#法式員常常用到的10個適用代碼片斷曾經和年夜家一路分享了,願望年夜家都能成為一個及格的C#法式員,盡力吧,童鞋。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved