[英]C# TargetInvocationException and FormatException
好的,我这里发生的情况很奇怪。 首先,我需要提供一些背景知识。 我正在为XNA引擎制作的游戏创建AI代理。 设置方式的方式是,人们应该使用代理的框架来生成一个.dll,游戏在运行时便会使用该.dll来加载代理。
我可以访问游戏的代码(因此我可以看到发生了什么),此时,我正在使用别人的代理作为自己的起点。 最近,对游戏(以及相应的框架)进行了一些更改,主要是在类和接口的名称上进行了更改,这意味着我必须加快代理的速度。 因此,在完成所有必要的更新以便能够使用新版本的框架编译代理后,我想到了一个问题。 这是游戏加载.dll的代码
// dynamically load assembly from file GeometryFriendsAgents.dll
Assembly agentsDLL = Assembly.LoadFile(path);
// get type of classes BallAgent and SquareAgent from just loaded Assembly
Type circleType = AgentsDLL.GetType("GeometryFriendsAgents.CircleAgent");
Type rectangleType = AgentsDLL.GetType("GeometryFriendsAgents.RectangleAgent");
try {
// create instances of classes BallAgent and SquareAgent
npcCircle = (ICircleAgent)Activator.CreateInstance(circleType);
npcRectangle = (IRectangleAgent)Activator.CreateInstance(rectangleType);
}catch(TargetInvocationException e){
throw e.InnerException;
}
我可以确认路径正确。 当我尝试运行游戏时,try / catch内的行将引发TargetInvocationException(这将自动加载代理)。 我添加了try / catch来查看内部异常,它是FormatException,并且VisualStudio提供了附加信息,即输入字符串的格式不正确。
我不知道代理程序代码的哪一部分与此相关,但是我还没有进入奇怪的部分。 在我正在使用的实现中,代理利用了LearningCenter类。 此类实际上是读写代理的学习文件。 在课程开始时,它存储学习文件的路径:
protected const string path = @"..\..\..\..\Agents\";
因此,这里的事情变得很奇怪。 这是学习文件的正确路径。 早些时候我犯了一个错误,我有这个路径(之前在整个代码中多次重复)
protected const string path = @"..\..\..\..\Agents";
当我使用错误的路径构建.dll时,我可以成功加载代理,它将运行游戏。 然后的问题是路径不正确,并且当LearningCenter尝试写入学习文件时,它显然会失败,并出现DirectoryNotFoundException。 有问题的方法是:
public void EndGame(float knownStatesRatio) {
if (_toSave) {
FileStream fileStream = new FileStream(path + _learningFolder + "\\Ratios.csv", FileMode.Append);
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(knownStatesRatio);
sw.Close();
fileStream.Close();
fileStream = new FileStream(path + _learningFolder + "\\IntraPlatformLearning.csv", FileMode.Create);
DumpLearning(fileStream, _intraplatformPlayedStates);
fileStream.Close();
if (interPlatform) {
fileStream = new FileStream(path + _learningFolder + "\\InterPlatformLearning.csv", FileMode.Create);
DumpLearning(fileStream, _interplatformPlayedStates);
fileStream.Close();
}
}
}
创建新文件流时立即发生异常。 我试图将缺少的\\
移到_learningFolder
变量,但是当我这样做时,它又回到了第一个问题。 只要路径不正确,我就可以运行游戏...
我还应该提到,在此之前,我最初在同一位置遇到了另一个TargetInvocationException。 当时,通过更改代理类对公众的可见性来解决此问题。
我意识到带有路径的东西可能隐藏了实际的问题,但是我只是不知道下一步该怎么看。
编辑:这是第一个问题的堆栈跟踪
GeometryFriends.exe!GeometryFriends.AI.AgentsManager.LoadAgents() Line 396
GeometryFriends.exe!GeometryFriends.Levels.SinglePlayerLevel.LoadLevelContent() Line 78
GeometryFriends.exe!GeometryFriends.Levels.Level.LoadContent() Line 262
GeometryFriends.exe!GeometryFriends.ScreenSystem.ScreenManager.LoadContent() Line 253
Microsoft.Xna.Framework.Game.dll!Microsoft.Xna.Framework.DrawableGameComponent.Initialize()
GeometryFriends.exe!GeometryFriends.ScreenSystem.ScreenManager.Initialize() Line 221
Microsoft.Xna.Framework.Game.dll!Microsoft.Xna.Framework.Game.Initialize()
GeometryFriends.exe!GeometryFriends.Engine.Initialize() Line 203
Microsoft.Xna.Framework.Game.dll!Microsoft.Xna.Framework.Game.RunGame(bool useBlockingRun)
Microsoft.Xna.Framework.Game.dll!Microsoft.Xna.Framework.Game.Run()
GeometryFriends.exe!GeometryFriends.Program.Main(string[] args) Line 16
首先失败的代理是CircleAgent,这是构造函数:
public CircleAgent() {
//Change flag if agent is not to be used
SetImplementedAgent(true);
lastMoveTime = DateTime.Now;
lastRefreshTime = DateTime.Now;
currentAction = 0;
rnd = new Random(DateTime.Now.Millisecond);
model = new CircleWorldModel(this);
learningCenter = new CircleLearningCenter(model);
learningCenter.InitializeLearning();
startTime = DateTime.Now;
}
编辑2:好吧,我设法在FormatException的源上。 在CircleLearningCenter的此方法中发生错误(第一个if中的语句):
public override void addStateMovementValue(string[] lineSplit, string stateId, ref Dictionary<string, Dictionary<int, double>> lessons) {
if (!lineSplit[1].Equals("0")) {
lessons[stateId].Add(Moves.ROLL_LEFT, double.Parse(lineSplit[1]));
}
if (!lineSplit[2].Equals("0")) {
lessons[stateId].Add(Moves.ROLL_RIGHT, double.Parse(lineSplit[2]));
}
if (!lineSplit[3].Equals("0")) {
lessons[stateId].Add(Moves.JUMP, double.Parse(lineSplit[3]));
}
}
在学习中心中通过此方法调用该方法:
private void createLearningFromFile(FileStream fileStream, ref Dictionary<string, Dictionary<int, double>> lessons) {
lessons = new Dictionary<string, Dictionary<int, double>>();
StreamReader sr = new StreamReader(fileStream);
string line;
while ((line = sr.ReadLine()) != null) {
string[] lineSplit = line.Split(',');
string stateId = lineSplit[0];
lessons.Add(stateId, new Dictionary<int, double>());
addStateMovementValue(lineSplit, stateId, ref lessons);
}
}
依次由该方法调用(在圆的构造函数中调用):
public void InitializeLearning() {
if (File.Exists(Path.Combine(Path.Combine(path, _learningFolder), "IntraPlatformLearning.csv"))) {
FileStream fileStream = new FileStream(Path.Combine(Path.Combine(path, _learningFolder),"IntraPlatformLearning.csv"), FileMode.Open);
createLearningFromFile(fileStream, ref _intraplatformLessonsLearnt);
fileStream.Close();
} else {
createEmptyLearning(ref _intraplatformLessonsLearnt);
}
if (File.Exists(Path.Combine(Path.Combine(path, _learningFolder), "InterPlatformLearning.csv"))) {
FileStream fileStream = new FileStream(Path.Combine(Path.Combine(path, _learningFolder), "InterPlatformLearning.csv"), FileMode.Open);
createLearningFromFile(fileStream, ref _interplatformLessonsLearnt);
fileStream.Close();
} else {
createEmptyLearning(ref _interplatformLessonsLearnt);
}
}
如果不清楚,CircleLearningCenter是LearningCenter的子类。 另外,对文本墙感到抱歉,但我不知所措。
使用System.IO.Path.Combine()连接路径部分。 例如:
代替 :
FileStream(path + _learningFolder + "\\Ratios.csv")
采用 :
FileStream(Path.Combine(Path.Combine(path , _learningFolder) , "Ratios.csv"))
只是不要忘记从每个部分中删除\\\\。 并对其他FileStream路径执行相同操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.