需要帮助理解代码

时间:2016-10-17 01:47:24

标签: c#

所以我正在进行的这个程序有精灵。每个精灵都有一个限制它的精灵可以拥有的帧数,我正在试图弄清楚如何学习这个限制,以便我可以修改它。但是我一直在阅读的代码对我来说真的很难。我一直在阅读它使用的一些内容(例如DictionaryOut),但是当我尝试将该读取应用于代码时,它就会崩溃。

呃,如果有人愿意分析代码并告诉我它的内容,那就太好了。可以找到here的全部内容,但这正是我特别想要阅读的内容:

class FrameData {
    Dictionary<FrameType, Dictionary<Enums.Direction, int>> frameCount;
}

public FrameData() {
    frameCount = new Dictionary<FrameType, Dictionary<Enums.Direction, int>>();
}

public void SetFrameCount(FrameType type, Enums.Direction dir, int count) {
    if (frameCount.ContainsKey(type) == false) {
        frameCount.Add(type, new Dictionary<Enums.Direction, int>());
    }
    if (frameCount[type].ContainsKey(dir) == false) {
        frameCount[type].Add(dir, count);
    } else {
        frameCount[type][dir] = count;
    }
}

public int GetFrameCount(FrameType type, Enums.Direction dir) {
    Dictionary<Enums.Direction, int> dirs = null;
    if (frameCount.TryGetValue(type, out dirs)) {
        int value = 0;
        if (dirs.TryGetValue(dir, out value)) {
            return value;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

1 个答案:

答案 0 :(得分:1)

//This bit declares the class.  note that all the stuff after it should come inside the open and closed curly braces, so there's already a syntax error here. 
class FrameData {
    Dictionary<FrameType, Dictionary<Enums.Direction, int>> frameCount;
}
// Public parameterless constructor. This gets called when someone creates an instance of the class, e.g. FrameData myframe = new FrameData()
public FrameData() {
    // initialize the instance variable frameCount with a new dictionary that takes a FrameType as the key and another dictionary of Enums.Direction and ints as key and value
    frameCount = new Dictionary<FrameType, Dictionary<Enums.Direction, int>>();
}
// Public method for adding or replacing a key and its value in the frameCount dictionary
public void SetFrameCount(FrameType type, Enums.Direction dir, int count) {
    // adds a new one if it didn't already have that key
    if (frameCount.ContainsKey(type) == false) {
        frameCount.Add(type, new Dictionary<Enums.Direction, int>());
    }
    // adds a new key to the inner dictionary if it's not there
    if (frameCount[type].ContainsKey(dir) == false) {
        frameCount[type].Add(dir, count);
    } else {
        // otherwise just replaces what was already there
        frameCount[type][dir] = count;
    }
}
// fetches the nested value from the inner dictionary given the type and direction
public int GetFrameCount(FrameType type, Enums.Direction dir) {
    Dictionary<Enums.Direction, int> dirs = null;
    if (frameCount.TryGetValue(type, out dirs)) {
        int value = 0;
        if (dirs.TryGetValue(dir, out value)) {
            return value;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}