Материал для тех, кто уже на чём-то писать умеет, и кому надо срочно что-то написать на C#. Это не шпаргалка для экзаменов, а набор примеров кода. Приведённых здесь примеров достаточно для 80% всего, что можно написать на C# даже без использования IDE (достаточно блокнота). Поехали.
= c#
== Самая короткая программа на C#, которая ничего не делает
class test {static void Main(){}}
== выход из программы
Quit();
return из Main
== компиляция
=== csc
csc form.cs
на выходе появится экзешник
=== mcs
mcs form.cs -r:System.Windows.Forms.dll
== консоль
Console.Write("Press any key to exit . . . ");
Console.ReadKey(true);
== подключение dll
[DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true, CharSet = CharSet.Unicode,
ThrowOnUnmappableChar = true)]
private static extern bool PlaySound(string szSound, System.IntPtr hMod, PlaySoundFlags flags);
== перебор массивов циклом
=== объявление
==== многомерный массив
int[] nums1 = new int[] { 0, 1, 2, 3, 4, 5 };
int[,] nums2 = { { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums1;
int[,] nums2 = new int[2, 3];
int[,] nums3 = new int[2, 3] { { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums4 = new int[,] { { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums5 = new [,]{ { 0, 1, 2 }, { 3, 4, 5 } };
int[,] nums6 = { { 0, 1, 2 }, { 3, 4, 5 } };
==== массив массивов
int[][] nums = new int[3][];
nums[0] = new int[2] { 1, 2 }; // выделяем память для первого подмассива
nums[1] = new int[3] { 1, 2, 3 }; // выделяем память для второго подмассива
nums[2] = new int[5] { 1, 2, 3, 4, 5 }; // выделяем память для третьего подмассива
=== for
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = numbers[i] * 2;
Console.WriteLine(numbers[i]);
}
=== foreach
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int i in numbers)
{
Console.WriteLine(i);
}
=== длина массива
int[] numbers = { 1, 2, 3, 5 };
Console.WriteLine(numbers.Length); // 4
=== элементы с конца
int[] numbers = { 1, 2, 3, 5};
Console.WriteLine(numbers[^1]); // 5 - последний элемент с конца
Console.WriteLine(numbers[^2]); // 3 - предпоследний элемент с конца
== чтение и запись файлов
=== чтение
string text = System.IO.File.ReadAllText(@"C:\tmp\Text.txt");
=== запись
var file = new System.IO.StreamWriter(this.textBoxOutputDir.Text + "\\log.txt", true);
file.WriteLine(OutText);
file.Close();
== http-запросы
using System.Net;
...
private static string POST(string Url, string Data)
{
WebRequest req = WebRequest.Create(Url);
req.Method = "POST";
req.Timeout = 100000;
req.ContentType = "application/x-www-form-urlencoded";
byte[] sentData = Encoding.GetEncoding(1251).GetBytes(Data);
req.ContentLength = sentData.Length;
Stream sendStream = req.GetRequestStream();
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
WebResponse res = req.GetResponse();
Stream ReceiveStream = res.GetResponseStream();
StreamReader sr = new StreamReader(ReceiveStream, Encoding.UTF8);
//Кодировка указывается в зависимости от кодировки ответа сервера
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
...
}
== Обработка исключений
static double SafeDivision(double x, double y)
{
if (y == 0)
throw new DivideByZeroException();
return x / y;
}
...
try
{
result = SafeDivision(a, b);
Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
}
catch (DivideByZeroException)
{
Console.WriteLine("Attempted divide by zero.");
}
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
// Do
== обработка аргументов
public static int Main(string[] args) {
if(args.Length > 1){
string Data="arg1:" + args[1];
...
}
}
== окна
=== создание окна
using System;
using System.Windows.Forms;
public class HelloWorld : Form {
static public void Main () {
Application.Run (new HelloWorld ());
}
public HelloWorld () {
Text = "Hello Mono World";
}
}
=== добавление кнопки
this.button1 = new System.Windows.Forms.Button();
this.button1.Location = new System.Drawing.Point(192, 40);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(88, 24);
this.button1.TabIndex = 0;
this.button1.Text = "Browse";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.Controls.Add(this.button1);
...
private void button1_Click(object sender, System.EventArgs e)
{
...
}
=== всё вместе
public class MainWindow : System.Windows.Controls.Window
{
private Button button1;
public MainWindow()
{
button1 = new Button();
button1.Text = "Click me!";
button1.ClickEvent += button1_OnClick;
}
protected void button1_OnClick(object sender, MouseEventArgs e)
{
MessageBox.Show("Clicked!");
}
}
== лямбды
(input-parameters) => expression
(input-parameters) => { <sequence-of-statements> }
Func<int, int> square = x => x * x;
Console.WriteLine(square(5));
// Output:
// 25
== xml
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
// Save the document to a file.
doc.Save("data.xml");
}
}
== sql
using System.Data.SqlClient;
string query = @"select 1";
using (
var connection = new SqlConnection(
"user id=Vasya;password=P@$$w0rd;server=MyServer;database=MyBase;connection timeout=10;"
)
) {
connection.Open();
using (var command = new SqlCommand(query, connection)){
command.CommandTimeout = 290;
using(SqlDataReader reader = command.ExecuteReader()){
int rowcounter = -1;
while (reader.Read()) {
rowcounter++; //счётчик строк в результате запроса
//заполняем значения в сохранённой строке
if (reader["My_Column"] is int) {
int n = (int)reader["My_Column "];
}
//…
}
reader.Close();
}
}
}
//добавить обработчики исключений
Для подключения к базе не под логином и паролем, а через доменную авторизацию
using (var connection = new SqlConnection("server=MyServer;database=MyBase;connection timeout=10; Integrated Security=True;")) {}
== Linq
using System.Linq;
using System.DirectoryServices;
...
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry
in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
foreach (var name in userNames)
Console.WriteLine(name);
}
var list = new List<int>{ 2, 7, 1, 3, 9 };
var result = from i in list
where i > 1
select i;
== операции со строками
// Declare without initializing.
string message1;
string message2 = null;
string message3 = System.String.Empty;
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";
string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";
System.String greeting = "Hello World!";
var temp = "I'm still a strongly-typed System.String!";
const string message4 = "You can't get rid of me!";
char[] letters = { 'A', 'B', 'C' };
string alphabet = new string(letters);
=== сложение
s1 += s2;
=== подстроки
string s3 = "Visual C# Express";
System.Console.WriteLine(s3.Substring(7, 2));
// Output: "C#"
=== поиск
int index = s3.IndexOf("C");
=== замена
System.Console.WriteLine(s3.Replace("C#", "Basic"));
=== перебор символов
s5[s5.Length - i - 1]
=== ToLower ToUpper
if (System.Char.IsLower(sb[j]) == true)
sb[j] = System.Char.ToUpper(sb[j]);
else if (System.Char.IsUpper(sb[j]) == true)
sb[j] = System.Char.ToLower(sb[j]);
=== форматированные строки
var jh = (firstName: "Jupiter", lastName: "Hammon", born: 1711, published: 1761);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
Console.WriteLine($"He was first published in {jh.published} at the age of {jh.published - jh.born}.");
Console.WriteLine($"He'd be over {Math.Round((2018d - jh.born) / 100d) * 100d} years old today.");
string name = "Vynn";
string greetings = string.Format("Hello {0}!", name);
string name = "Vjor";
string greeting = $"Hello, {name}!";
=== многострочные строки
string query = @"
SELECT *
FROM some_table
"
@"C:\tmp\Text.txt"
=== unicode
string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
== Словари
var jh = (
firstName: "Jupiter",
lastName: "Hammon",
born: 1711,
published: 1761
);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
var numbers = new Dictionary<int, string>
{
[7] = "seven",
[9] = "nine",
[13] = "thirteen"
};
foreach (KeyValuePair<string, List<string>> group in rudimentaryMultiValuedDictionary1){
...
}
== задержка времмени в программе
System.Threading.Thread.Sleep(50);
== многопоточность
public async Task<int> RetrieveDocsHomePage()
{
var client = new HttpClient();
byte[] content = await client.GetByteArrayAsync("https://docs.microsoft.com/");
Console.WriteLine($"{nameof(RetrieveDocsHomePage)}: Finished downloading.");
return content.Length;
}
Thread synchronization
C# provides the lock statement, which is yet another example of beneficial syntactic sugar. It works by marking a block of code as a critical section by mutual exclusion of access to a provided object. Like the using statement, it works by the compiler generating a try ... finally block in its place.
private static StreamWriter _writer;
public void ConcurrentMethod()
{
lock (_writer)
{
_writer.WriteLine("Line 1.");
_writer.WriteLine("Followed by line 2.");
}
}
== асинхронность
static IEnumerable<int> MyIterator()
{
try
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
yield return i;
}
}
finally
{
Thread.Sleep(200);
Console.WriteLine("finally");
}
}
static async IAsyncEnumerable<int> MyIterator()
{
try
{
for (int i = 0; i < 100; i++)
{
await Task.Delay(1000);
yield return i;
}
}
finally
{
await Task.Delay(200);
Console.WriteLine("finally");
}
}
IAsyncEnumerable<string> result = from url in urls
where item % 2 == 0
select SomeAsyncMethod(item);
async ValueTask<int> SomeAsyncMethod(int item)
{
await Task.Yield();
return item * 2;
}
public static class SomeAsyncCode
{
public static Task<XDocument> GetContentAsync()
{
HttpClient httpClient = new HttpClient();
return httpClient.GetStringAsync("www.contoso.com").ContinueWith((task) => {
string responseBodyAsText = task.Result;
return XDocument.Parse(responseBodyAsText);
});
}
}
var t = SomeAsyncCode.GetContentAsync().ContinueWith((task) => {
var xmlDocument = task.Result;
});
t.Start();
Here is the same logic written in the async-await syntax:
public static class SomeAsyncCode
{
public static async Task<XDocument> GetContentAsync()
{
HttpClient httpClient = new HttpClient();
string responseBodyAsText = await httpClient.GetStringAsync("www.contoso.com");
return XDocument.Parse(responseBodyAsText);
}
}
var xmlDocument = await SomeAsyncCode.GetContentAsync();
// The Task will be started on call with await.
== Запуск команд CMD из кода программы
using System.Diagnostics;
Process.Start("calc");
Process.Start("explorer", "d:");
Так же можно запускать программы от имени другого пользователя, см. вамианты перегрузки .Start()
== тесты
[TestMethod]
public void Debit_WithValidAmount_UpdatesBalance()
{
double beginningBalance = 11.99;
double debitAmount = 4.55;
double expected = 7.44;
BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);
account.Debit(debitAmount);
double actual = account.Balance;
Assert.AreEqual(expected, actual, 0.001, "Account not debited correctly");
}
[TestMethod]
public void Debit_WhenAmountIsMoreThanBalance_ShouldThrowArgumentOutOfRange()
{
double beginningBalance = 11.99;
double debitAmount = 20.0;
BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);
try {
account.Debit(debitAmount);
}
catch (System.ArgumentOutOfRangeException e) {
// Assert
StringAssert.Contains(e.Message, BankAccount.DebitAmountExceedsBalanceMessage);
return;
}
Assert.Fail("The expected exception was not thrown.");
}
== прочее
=== пространства имён
using forwpf = System.Windows;
...
public static forwpf::Point Convert(forwinforms::Point point) => new forwpf::Point(point.X, point.Y);
=== узнать текущее имя пользователя
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
=== какая вкладка открыта в tabControl
this.tabControl1.SelectedTab – сама выбранная вкладка
this.tabControl1.SelectedTab.Text – её заголовок
tabControl1.SelectTab(1); — выбрать вкладку по номеру
=== get, set
public int Y
{
get { return y; }
set { y = value; }
}
struct Point
{
int X;
int Y {get; set;}
}
=== операторы
System.Index operator ^(int fromEnd);
=== обход файлов и папок
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
{
System.Console.WriteLine(s);
}
=== stdin, out, err
System.Console.WriteLine(sb.ToString());
System.Console.ReadLine();
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
=== HEX
byte[] array = { 0x64, 0x6f, 0x74, 0x63, 0x65, 0x74 };
string hexValue = Convert.ToHexString(array);
/*Output:
646F74636574
*/
=== списки
System.Collections.Generic.List<string> strings = new System.Collections.Generic.List<string>();
List<Cat> cats = new List<Cat>
{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};
.at(...)
=== операторы
Primary expressions Primary x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate
Unary operators Unary + - ! ~ ++x --x (T)x
Arithmetic operators Multiplicative * / %
Arithmetic operators Additive + -
Shift operators Shift << >>
Relational and type-testing operators Relational and type testing < > <= >= is as
Relational and type-testing operators Equality == !=
Logical operators Logical AND &
Logical operators Logical XOR ^
Logical operators Logical OR |
Conditional logical operators Conditional AND &&
Conditional logical operators Conditional OR ||
The null coalescing operator Null coalescing ??
Conditional operator Conditional ?:
Assignment operators, Anonymous function expressions Assignment and lambda expression = *= /= %= += -= <<= >>= &= ^= |= =>
=== колбэки
public static void MethodWithCallback(int param1, int param2, Del callback)
{
callback("The number is: " + (param1 + param2).ToString());
}
=== if else
int statusCode = condition ? 1 : 2;
=== switch
switch (condition)
{
case 1:
//do something
break;
case 2:
//do something
break;
case 3:
//do something
break;
default:
//do something else
break;
}
=== Tuples
public (string FirstName, string LastName) GetName()
{
return ("Vincent", "Durano");
}
=== делегаты
class Program
{
// Delegate type:
delegate int Operation(int a, int b);
static int Add(int i1, int i2)
{
return i1 + i2;
}
static int Sub(int i1, int i2)
{
return i1 - i2;
}
static void Main()
{
// Instantiate the delegate and assign the method to it.
Operation op = Add;
// Call the method that the delegate points to.
int result1 = op(2, 3); // 5
op = Sub;
int result2 = op(10, 2); // 8
}
}
=== указатели
static void Main(string[] args)
{
unsafe
{
int a = 2;
int* b = &a;
Console.WriteLine("Address of a: {0}. Value: {1}", (int)&a, a);
Console.WriteLine("Address of b: {0}. Value: {1}. Value of *b: {2}", (int)&b, (int)b, *b);
// Will output something like:
// Address of a: 71953600. Value: 2
// Address of b: 71953596. Value: 71953600. Value of *b: 2
}
}
=== анонимные типы
var carl = new { Name = "Carl", Age = 35 }; // Name of the type is only known by the compiler.
=== Boxing and unboxing
int foo = 42; // Value type.
object bar = foo; // foo is boxed to bar.
int foo2 = (int)bar; // Unboxed back to value type.
=== модификаторы
Class modifiers
abstract - Specifies that a class only serves as a base class. It must be implemented in an inheriting class.
sealed - Specifies that a class cannot be inherited.
Class member modifiers
const - Specifies that a variable is a constant value that has to be initialized when it gets declared.
event - Declares an event.
extern - Specifies that a method signature without a body uses a DLL-import.
override - Specifies that a method or property declaration is an override of a virtual member or an implementation of a member of an abstract class.
readonly - Declares a field that can only be assigned values as part of the declaration or in a constructor in the same class.
unsafe - Specifies an unsafe context, which allows the use of pointers.
virtual - Specifies that a method or property declaration can be overridden by a derived class.
volatile - Specifies a field which may be modified by an external process and prevents an optimizing compiler from modifying the use of the field.
static modifier
=== интерфейсы
public class Adder : IBinaryOperation
{
double IBinaryOperation.A { get; set; }
double IBinaryOperation.B { get; set; }
double IBinaryOperation.GetResult()
{
return ((IBinaryOperation)this).A + ((IBinaryOperation)this).B;
}
}
In use:
Adder add = new Adder();
// These members are not accessible:
// add.A = 2;
// add.B = 3;
// double result = add.GetResult();
// Cast to the interface type to access them:
IBinaryOperation add2 = add;
add2.A = 2;
add2.B = 3;
double result = add2.GetResult();
class MyClass : IInterfaceA, IInterfaceB
{
...
}
Here is an interface that extends two interfaces.
interface IInterfaceC : IInterfaceA, IInterfaceB
{
...
}
=== Шаблоны типов
public class GenericList<T>
{
void Add(T input) { }
}
=== Генераторы
public static IEnumerable<int> GetEven(IEnumerable<int> numbers){
foreach (int i in numbers){
if (i%2 == 0)
yield return i;
}
}
=== XML documentation system
public class Foo
{
/** <summary>A summary of the method.</summary>
* <param name="firstParam">A description of the parameter.</param>
* <remarks>Remarks about the method.</remarks> */
public static void Bar(int firstParam) {}
}
=== ...
Do use the using statement when working with objects that eat resources or implements IDisposable interface:
using (MemoryStream stream = new MemoryStream())
{
// do something
}
Try to avoid one-liner method implementation with curly braces like in the following:
public string Greeter(string name)
{
return $"Hello {name}!";
}
+1 Do use Expression-bodied (=>) implementation instead:
public string Greeter(string name) => $"Hello {name}!";
public struct Point { ... } // defines a “value” type
public class Pen { ... } // defines a “reference” type
=== ссылки
https://github.com/justinamiller/DotNet-Coding-Guidelines/blob/main/README.md
https://en.wikipedia.org/wiki/C_Sharp_syntax
Если чего-то всем нужного здесь не нашли, можно писать в комментариях.