class ArrayComparer : IComparer<int[]>
{
public int Compare(int[] x, int[] y)
{
if (x is null || y is null) throw new ArgumentNullException();
if (x.Length < 2 || y.Length < 2) throw new ArgumentException("Сравниваемые массивы должны иметь минимум 2 элемента");
int comparisonResult = x[0].CompareTo(y[0]);
if (comparisonResult == 0) comparisonResult = x[1].CompareTo(y[1]);
return comparisonResult;
}
}
...
_serialPort.Open();
_serialPort.DiscardInBuffer();
_serialPort.DataReceived += SerialPort_DataReceived;
_serialPort.ErrorReceived += SerialPort_ErrorReceived;
...
public static void Disconnect()
{
try
{
if (_serialPort is not null && _serialPort.IsOpen)
{
_serialPort.DataReceived -= SerialPort_DataReceived;
_serialPort.ErrorReceived -= SerialPort_ErrorReceived;
_serialPort.Close();
}
} // try
catch(Exception ex)
{
Log.Error(ex, "Error closing the serial port.");
} //
} // Disconnect
...
private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (_serialPort?.IsOpen != true) return;
try
{
var encoding = _serialPort.Encoding;
var bytesRead = _serialPort.Read(_buffer, 0, _serialPort.BytesToRead);
var rawBytes = new ReadOnlyMemory<byte>(_buffer, 0, bytesRead);
var maxCharCount = encoding.GetMaxCharCount(bytesRead);
var charArray = ArrayPool<char>.Shared.Rent(maxCharCount);
var charsProduced = encoding.GetChars(
rawBytes.Span,
charArray.AsSpan()
);
var scannedData = new ScannedData(
rawBytes,
new ReadOnlyMemory<char>(charArray, 0, charsProduced)
);
IncomingData.Enqueue(scannedData);
DataReceived?.Invoke(null, new DataReceivedEventArgs(scannedData));
ArrayPool<char>.Shared.Return(charArray);
} // try
catch (Exception ex)
{
Log.Error(ex, "Error processing barcode data");
} // catch
} // _serialPort_DataReceived
public class HappyGreeter : IGreeter
{
private interface IWorkAround : IGreeter
{
public void SayHello(string name)
{
(this as IGreeter).SayHello(name);
System.Console.WriteLine("I hope you're doing great!!");
}
}
private class WorkAround : IWorkAround {}
public void SayHello(string name)
{
((IWorkAround)new WorkAround()).SayHello(name);
}
}
Console.InputEncoding = System.Text.Encoding.GetEncoding("utf-16");
Console.WriteLine("Hello, World!");
var ans = Console.ReadLine();
Console.WriteLine(ans);
using System.Management;
public static Dictionary<string, ManagementBaseObject> EnumerateComPorts()
{
Dictionary<string, ManagementBaseObject> result = new Dictionary<string, ManagementBaseObject>();
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
using (var entitySearcher = new ManagementObjectSearcher(
"root\\CIMV2", $"SELECT * FROM Win32_PnPEntity WHERE Caption LIKE '%{port}%'"))
{
var matchingEntity = entitySearcher.Get().Cast<ManagementBaseObject>().FirstOrDefault();
if (null != matchingEntity)
{
result.Add(port, matchingEntity);
}
} // using
} // foreach
return result;
} // EnumerateComPorts
public RS232Listener(string portname)
{
m_queue = new Queue<string>();
try
{
if (null != m_port)
{
m_port.Close();
m_port.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
}
m_port = new SerialPort(portname, 9600, Parity.None, 8, StopBits.One);
m_port.DataReceived += this.M_port_DataReceived;
m_port.ErrorReceived += this.M_port_ErrorReceived;
m_port.Open();
} // try
catch(Exception ex)
{
Logger.LogError("RS232Listener constructor", ex.Message, ex);
ErrorMessage = ex.Message;
ErrorState = true;
}
} // RS232Listener constructor
using System;
using System.Linq;
class SplitToUpper {
static void Main() {
var input = "Это тестовое предложение, Некоторые из Слов начинаются с Заглавной буквы";
var words = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var output = words.Where(w => char.IsUpper(w[0])).Reverse().ToArray();
foreach(var word in output)
Console.WriteLine(word);
} // Main
} // class SplitToUpper
Заглавной
Слов
Некоторые
Это
num == "q" || num == "Q"
- есть методы .ToLower(), ToUpper(). Название переменной num абсолютно нелогично, если оно не числовое.using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static List<int> _numbers = new List<int>();
static void Main() {
while(UserInput(Console.ReadLine()));
Console.WriteLine($"Sum is: {CalcSum(_numbers)}");
}
static bool UserInput(string input)
{
if(string.IsNullOrEmpty(input)) return false;
if(!int.TryParse(input, out int number)) return false;
_numbers.Add(number);
return true;
}
static int CalcSum(IEnumerable<int> numbers)
{
return numbers.Sum();
}
}