Excepción tipo de inicialización cuando se utiliza un campo estático
-
29-09-2019 - |
Pregunta
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TypeIntailization_Exception
{
class TypeInit
{
// Static constructor
static TypeInit()
{
}
static readonly TypeInit instance = new TypeInit();
public static TypeInit Instance
{
get { return instance; }
}
TypeInit() { }
}
class TestTypeInit
{
static public void Main()
{
TypeInit t = TypeInit.Instance;
}
}
}
cuando se ejecuta este tipo me sale intialization Excepción cómo puedo evitar esto ...
Solución
El TypeInitializationException se inicia cuando se produce una excepción por el inicializador de la clase (en su ejemplo static TypeInit()
.
Se puede ver la verdadera excepción mediante el examen de la propiedad de la InnerException
TypeInitializationException:
static public void Main()
{
try
{
TypeInit t = TypeInit.Instance;
}
catch (TypeInitializationException tiex)
{
var ex = tiex.InnerException;
Console.WriteLine("Exception from type init: '{0}'", ex.Message);
}
}
Otros consejos
usted está lanzando una excepción en el constructor de la clase Singleton, por lo que el momento en que se está tratando de construirlo lanza una excepción. Esto se envuelve en el TypeInitializationException como ves.
Solución:. No se debe lanzar una excepción a menos que se warrented
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow