Weitere ähnliche Inhalte Ähnlich wie 04 standard class library c# (20) Mehr von Victor Matyushevskyy (20) Kürzlich hochgeladen (20) 04 standard class library c#2. Зміст
1. Що таке Generic? Extension methods.
2. Math
3. DateTime, TimeSpan
4. Regex
5. Колекції. System.Collections, System.Collections.Generic.
6. Nullable<T>, “type?”
7. Path
8. DriveInfo
9. Directory
10. File
11. Encodings
12. Streams
13. Serializationdeserializations
3. Generics
• Generic methods:
• FirstOrDefault<T>(T[] array)
• FirstOrDefault<T>(T[] array, T defaultValue)
• Type inference:
• int first = FirstOrDefault(new[] {3, 2, 1});
• default(T) expression
• Type constraints:
• Base type, class, struct, new()
• Generic types:
• Example: List<T>
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
4. Extension methods
Simply static methods
Used for convenience
http://msdn.microsoft.com/en-us/library/bb383977.aspx
5. Math
• Math.Abs(number)
• Math.Pow(number)
• Math.Sin(angle)
• Math.Cos(angle)
• Math.Max(number1, number2)
• Math.Min(number1, number2)
• …
http://msdn.microsoft.com/en-us/library/system.math.aspx
6. DateTime
• DateTime – представляє значення дати та часу.
• DateTime.Add(timeSpan)
• DateTime.AddDay(number)….
• DateTime.ToString(format) (hh:mm:ss)
• ToLocalTime()
• ToUniversalTime()
• DateTime.Now
• DateTime.UtcNow
• …
• TimeSpan – представляє інтервали дати та часу.
• TimeSpan.TotalMilliseconds
• TimeSpan.Days
• TimeSpan.TotalDays
• …
http://msdn.microsoft.com/en-us/library/system.datetime.aspx - DateTime
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx - Custom DateTime Formats
7. Regex
Email pattern: “b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}b”
• Regex.IsMatch(pattern, string)
• Regex.Replace(pattern, string, newValue)
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
8. Collections
Collections:
• Hashtable
• ArrayList
• Queue
• Stack
Collections.Generic:
• Dictionary<TKey, TValue>
• List<T>
• Queue<T>
• Stack<T>
• LinkedList<T>
http://msdn.microsoft.com/en-us/library/system.collections.aspx - Collections
http://msdn.microsoft.com/en-us/library/0sbxh9x2.aspx - Collections.Generic
9. Nullable<T>
int? = Nullable<int>
Useful properties:
• HasValue
• Value
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
10. Path
• Path.Combine(path1, path2)
• Path.GetDirectoryName(path)
• Path.GetFileName(path)
• Path.GetExtension(path)
• Path.GetFullPath(path)
• Path.GetRandomFileName()
• Path.GetTempFileName()
• Path.GetTempPath()
http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx
11. DriveInfo
• DriveInfo.GetDrives()
• drive.DriveType {CDRom, Fixed, Unknown, Network, Removable ….}
• drive.DriveFormat {NTFS, FAT32}
• drive. AvailableFreeSpace
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
12. Directory
• Directory.Create(folderPath)
• Directory.Move(folderPath, destinationPath)
• Directory.Delete(folderPath) && Directory.Delete(folderPath, true/*recursive*/)
• Directory.Exists(folderPath)
• Directory.GetFiles(folderPath, [search pattern])
http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
13. File
• File.Create(filePath)
• File.Move(filePath, filePathDestination)
• File.Copy(filePath, filePathDestination)
• File.Delete(filePath)
• File.Exists(filePath)
• File.WriteAllText(filePath, text)
• File.WriteAllBytes(filePath, bytes)
• File.AppendText(filePath, text)
• File.ReadAllText(filePath)
• File.ReadAllBytes(filePath)
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
14. Encoding
• Encoding.Default
• Encoding.Unicode
• Encoding.ASCII
• Encoding.UTF32
• …
• Encoding.Convert(sourceEncoding, destinationEncoding, bytes)
• encoding.GetBytes(string)
• encoding.GetString(bytes)
http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
15. Streams
• stream.Read(data, offset, count) Stream
• stream.Write(data, offset, count)
• stream.Length
CryptoStream
• stream.Seek(offset, SeekOrigin)
• stream.Close() MemoryStream
FileStream
• StreamWriter – easy way to write into text files.
• StreamReader – easy way to read text from files.
• FileStream – easy way to work with binary files.
Create FileStream:
• constructor (new FileStream(path, FileMode, FileAccess))
• File.Create
• File.Open
• File.Write
http://msdn.microsoft.com/en-us/library/system.io.stream.aspx - Stream
http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx - FileStream
16. Binary serialization
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
Serizalization
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
Deserizalization
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);
stream.Close();
http://msdn.microsoft.com/en-us/library/72hyey7b(v=vs.80).aspx
17. XML serialization
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
Serizalization
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
serializer.Serialize(stream, obj);
stream.Close();
Deserizalization
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)serializer.Deserialize(stream);
stream.Close();
http://msdn.microsoft.com/en-us/library/90c86ass(v=vs.80).aspx
Hinweis der Redaktion Важливість збереження UTCБаг з збереженням тільки дати. (ЮТС і потім проблема конвертацією до ЛокалТайм) The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProvider interface) and the Object.Equals method (or the IComparer interface). Path.Combine(“c:\\folder1\\”, “\\folder2\\fileName.txt”)GetDirectoryName('C:\\MyDir\\MySubDir\\myfile.ext') returns 'C:\\MyDir\\MySubDir‘GetFileName('C:\\mydir\\myfile.ext') returns 'myfile.ext‘// GetFullPath('mydir') returns 'C:\\temp\\Demo\\mydir'// GetFullPath('\\mydir') returns 'C:\\mydir' Rename - move File.Create returns Stream!Rename - move fs.Seek(offset, SeekOrigin.Begin)fs.Write(data, 0, data.length) Приавила серіалізаціїАтрибув [Serializable]Public\\private\\protected клас Приавила серіалізаціїДефолтний конструкторpublic класpublic проперті\\філдиЯкщо під час десеріалізації не знаходиться властивість у даних, то в об’єкті вона буде null