只能在Type.IsGenericParameter为true的Type上调用Method,而对于' XYZ'抛出一个例外

时间:2016-09-30 14:46:16

标签: c# reflection

我有一个类似的设置:

Program.cs
{
     public static void Main(string[] args)
     {
          XYZ.SomeMethod(); //--> XYZ is accessed for the firsttime here
     }

     private void OnDBInstall(object sender, EventArgs e)
     {
          //after Db install is complete
          if(success)
          {
               InvokeMethod(SomeEvent) //-->this is the second time XYZ is accessed
          }
     }
}

public static class Utility
{
     public static void InvokeSomeMEthods(EventHandler<T> h)
     {
          if(h!=null)
          {
               foreach(EventHandler<T> eh in h.GetInvocationList())
               {
                   eh.Invoke(null, EventArgs.Empty);
               }
          }
     }
}

public static class XYZ
{
     private static XYZCache _cache = new XYZCache();

     static XYZ()
     {
          SomeEvent += OnSomeEvent;
          _cache.Initialize();
     }

     static void OnSomeEvent(object sender, EventArgs e)
     {
          _cache.Initialize();
     }

     static void SomeMethod()
     {
          //some db call
     } 
}


internal class XYZCache
{
     internal void Initialize()
     {
          //some db call
     }
}

我在不同阶段得到多个例外。当我第一次调用XYZ.SomeMethod()时,我得到了&#34;无法打开数据库&#34; ..&#34;登录请求。登录失败&#34;。好的,这很好,因为数据库在那时并不存在。在进行任何Db调用之前,我应该先检查数据库是否存在。这个例外没有处理。

然后我在eh.Invoke获得了其他例外(此时DB已创建并可用):&#34;&#39; XYZ&#39;的类型初始值设定项引发异常&#34;,&#34;方法只能在Type.IsGenericParameter为真的Type上调用。&#34;,我也得到&#34;无法打开数据库&#34; ..& #34;登录请求。登录失败&#34;。当我得到这些异常时,甚至不调用XYZ类中的OnSomeEvent,因此不访问_cache。

&#34;&#39; XYZ&#39;的类型初始值设定项提出异常&#34;这是非常误导的,因为这不是第一次访问XYZ。

如果XYZ.SomeMethod()被try catch包装,那么一切都很好。有没有办法处理这种情况没有尝试捕获?由于一些奇怪的原因,我也无法检查数据库是否存在。

注意:我已经阅读了这篇文章,这非常有用:Method may only be called on a Type for which Type.IsGenericParameter is true

0 个答案:

没有答案