Type Initialization Exception when using a static field
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TypeIn开发者_运维技巧tailization_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;
}
}
}
when running this i get Type InTialization Exception how can i avoid this...
The TypeInitializationException is thrown when an exception is thrown by the class initializer (in your example static TypeInit()
.
You can see the real exception by examining the InnerException
property of the 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);
}
}
You are throwing an exception in the constructor of your singleton class, so the moment you are trying to construct it it throws an exception. This gets wrapped in the TypeInitializationException as you see.
Solution: don't throw an exception unless it is warrented.
精彩评论