0

给定两个字符串,比如 hashKey 和 hashVal,我将这对添加到一个哈希对象中。在此示例中,hashVal 是一个表示整数的字符串,因此我在将其存储到表中之前对其进行解析。

现在问题来了。存储在哈希表中的值实际上是一个 int32 对象,这使得后面在内部表达式中使用起来很麻烦。经过长时间的寻找,我一​​直无法找到一种简单的方法来存储实际的 int 或提取存储为 int 而不是 int32 对象的值。

下面是我正在尝试做的一个例子:

var myHash : HashObject;
var intTemp : int;
var hashKey : String;
var hashVal : String;
hashKey = "foobar";
hashVal = "123";

if(System.Int32.TryParse(hashVal,intTemp)) 
{
    intTemp = int.Parse(hashVal);
    myHash.Add(hashKey,hashVal);
}

// later, attempt to retrieve and use the value:

var someMath : int;
someMath = 456 + myHash["foobar"];

这会产生编译时错误:
BCE0051:运算符“+”不能与“int”类型的左侧和“Object”类型的右侧一起使用。

如果我尝试转换对象,则会收到运行时错误:
InvalidCastException:无法从源类型转换为目标类型。

我知道我可以先将检索到的值存储在一个新的 int 中,然后再使用它,但这对于我将使用的数学数量和键值对的数量来说将是一个非常冗长且不优雅的解决方案,因此主要否定首先使用哈希表的好处。

有任何想法吗?

4

3 回答 3

0

为什么不存储表中的hashVal和的元组而不仅仅是存储?然后您可以直接从查找中访问数字值intTemphashVal

if(System.Int32.TryParse(hashVal,intTemp)) {
    intTemp = int.Parse(hashVal);
    myHash.Add(hashKey, { hashValue : hashVal, intValue : intTemp });
}

var someMath : int;
someMath = 456 + myHash["foobar"].intValue;
于 2013-03-12T00:37:23.740 回答
0

我不熟悉统一脚本中的“HashObject”。您可以改用 HashTable 吗?:

var myHash: Hashtable;

function Start() {
    myHash = new Hashtable();
    myHash.Add("one",1);
    myHash.Add("two",2);
}
function Update () {
    var val = myHash["one"] + myHash["two"] + 3;
    Debug.Log("val: " + val);
}

同样在您的原始示例中,您将字符串值分配给哈希表,从未使用过 intTemp。

于 2013-03-12T12:44:46.697 回答
0
C# : The easiest hash solution in Unity is the HashSet:
https://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx

(You have to include the System.Collections.Generic library)

Very simple usage, O(1) speed

// create - dont even worry setting the size it is dynamic, it will also do the hash function for you :) 

private HashSet<string> words = new HashSet<string>();

// add- usually read from a file or in a for loop etc

words.Add(newWord);

// access via other other script such as

if (words.Contains(wordToCheck)) 
  return true;
于 2015-12-16T11:42:25.527 回答