我无法在客户端应用程序中从通用抽象类中捕获异常。我希望在构造函数中抛出异常的原因是,配置文件功能需要在派生类中相同,因此我认为没有理由在每个派生类中实现这个功能。但是,应该在总体通用类AgentModule<T>
中处理异常,然而,出于某种原因,我不知道为什么不能这样做。
当我将代码移动到方法中并从客户端类调用时,我可以捕获异常。
抽象类:
public abstract class Importer
{
public abstract string Name { get; }
public abstract string Description { get; }
private System.Configuration.Configuration _customConfig;
public Importer()
{
string customConfigFile = this.GetType().Assembly.Location + ".config";
if (System.IO.File.Exists(customConfigFile))
{
System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
fileMap.ExeConfigFilename = customConfigFile;
_customConfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
}
else
{
throw new System.IO.FileNotFoundException("Could not load configuration file: " + customConfigFile);
}
}
public abstract void Load(ILogger logger);
}
通用的总体类:
public class AgentModule<T> : ModuleBase where T : Importer, new()
{
private Importer _importer;
public override void Run()
{
try
{
_importer = (Importer)Activator.CreateInstance<T>();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
派生类:
public class XLoad : Importer
{
public override string Name { get { return _name; } }
public override string Description { get { return _description; } }
private string _name;
private string _description;
public XLoad()
{
_name = "Load";
_description = "some desc";
}
public override void Load(ILogger logger)
{
Console.WriteLine("I am loading");
}
}
catch
块。 - Dimt