「C#Developer。Professional」コースの差し迫った開始の一環として、資料の翻訳を用意しました。また、無料のデモレッスン「C#用DIコンテナ」にもぜひご参加ください。このレッスンでは、次のことを行います。1)DIの原則とは何か、なぜそれが必要なのかを理解します。2)コンテナを使用せずにDIを適用する方法を学びます。3)C#用の2つの人気のあるDIコンテナを考えてみましょう:WindsorとAutofac、それらの長所と短所を分析しましょう。4)依存性の登録、ライフサイクルの管理、依存性注入の適用方法を学習します。
. - ( , ). C#.
. , « » . . , try/catch
:
try
{
try
{
// - , SpecificException
}
catch (SpecificException specificException)
{
log.LogError(specificException, "Specific error");
}
// -
}
catch (Exception exception)
{
log.LogError(exception, "General erro");
}
, , , try/catch
, . SpecificException
catch
, . :
catch (SpecificException specificException)
{
// ...
throw specificException;
}
:
catch (SpecificException specificException)
{
// ...
throw;
}
, SpecificException
, , . .
. Exception, Data. . , , . elmah.io
Data Data.
Data /:
var exception = new Exception("En error happened");
exception.Data.Add("user", Thread.CurrentPrincipal.Identity.Name);
throw exception;
user
, .
, . try/catch
:
try
{
service.SomeCall();
}
catch (Exception e)
{
e.Data.Add("user", Thread.CurrentPrincipal.Identity.Name);
throw;
}
, SomeCall
, . throw
catch
.
, - , :
try
{
File.WriteAllText(path, contents);
}
catch (Exception e)
{
logger.Error(e);
}
Exception
. , .NET, , . — , .
, :
try
{
File.WriteAllText(path, contents);
}
catch (ArgumentException ae)
{
Message.Show("Invalid path");
}
catch (DirectoryNotFoundException dnfe)
{
Message.Show("Directory not found");
}
catch (Exception e)
{
var supportId = Guid.NewGuid();
e.Data.Add("Support id", supportId);
logger.Error(e);
Message.Show($"Please contact support with id: {supportId}");
}
ArgumentException
DirectoryNotFoundException
Exception
, . , . Exception
support id
, ( , ) .
, , , , — . :
, . , , .
— NullReferenceException
. null
, null
. , NullReferenceException
:
Address a = null;
var city = a.City;
a . , , a .
city
, , null-condition
:
Address a = null;
var city = a?.City;
?
a C# , null
. city
null
.
— . FormatException
:
var i = int.Parse("invalid");
invalid
. try/catch
, int
, , , 1000 :
if (int.TryParse("invalid", out int i))
{
}
, invalid
int
, TryParse
true
i
. .
, Java- ( .NET -). . , - Java, .NET C#. , , . , , Data:
public class MyVerySpecializedException : Exception
{
public MyVerySpecializedException() : base() {}
public MyVerySpecializedException(string message) : base(message) {}
public MyVerySpecializedException(string message, Exception inner) : base(message, inner) {}
public int Status { get; set; }
}
MyVerySpecializedException
(, , :D) , . , Status . :
try
{
service.SomeCall();
}
catch (MyVerySpecializedException e) when (e.Status == 500)
{
// Do something specific for Status 500
}
catch (MyVerySpecializedException ex)
{
// Do something general
}
when
, MyVerySpecializedException
, Status 500. catch MyVerySpecializedException
.
. :
try
{
service.SomeCall();
}
catch
{
//
}
, — , . , , , . .
, NLog Serilog. - ASP.NET (Core), elmah.io .