0

hashKey と hashVal などの 2 つの文字列が与えられた場合、そのペアをハッシュ オブジェクトに追加します。この例では、hashVal は整数を表す文字列であるため、テーブルに格納する前にそのように解析します。

ここで問題です。ハッシュ テーブルに格納されている値は、実際には int32 オブジェクトであるため、後で式内で使用するのが面倒になります。長い間調べた結果、実際の int を格納するか、int32 オブジェクトではなく int として格納されている値を抽出する簡単な方法を見つけることができませんでした。

以下は、私がやろうとしていることの例です:

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

Unityスクリプトの「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 に答える
0

hashValだけでなく、と のタプルをintTempテーブル内に格納してみませんhashValか? 次に、ルックアップから数値に直接アクセスできます

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 に答える