문제

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;

        }
    }

}

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top