Genel bir istisna sınıfının tüm çeşitlerini yakalamak istiyorum ve bunu birden fazla catch bloğu olmadan yapmanın bir yolu olup olmadığını merak ediyordum. Örneğin, bir istisna sınıfım olduğunu varsayalım:
public class MyException<T> : Exception
{
public string MyProperty { get; }
public MyException(T prop) : base(prop.ToString())
{
MyProperty = prop?.ToString();
}
}
ve iki türetilmiş sınıf:
public class MyDerivedStringException : MyException<string>
{
public MyDerivedStringException(string prop) : base(prop)
{
}
}
public class MyDerivedIntException : MyException<int>
{
public MyDerivedIntException(int prop) : base(prop)
{
}
}
Her iki alıcı bir yolu yoktur MyDerivedStringExceptionve MyDerivedIntExceptionbir catch bloğunda.
Bunu denedim:
try
{
...
}
catch(Exception e) when (e is MyDerivedStringException || e is MyDerivedIntException)
{
}
ama çok temiz değil ve erişimim olmadığı anlamına geliyor MyProperty.
Soruna genel bir çözümle ilgileniyorum, ancak benim durumumda, genel İstisna, aşağıda belirtildiği gibi, soruna bazı ek kısıtlamalar ekleyen bir üçüncü taraf kütüphanesinde tanımlanmıştır.
Exceptionve iyiMyException<T>olurdu.