5

作成したメソッドの呼び出しに問題があります。

私が呼び出している方法は次のとおりです

public bool GetValue(string column, out object result)
{
    result = null;
    // values is a Dictionary<string, object>
    if (this._values.ContainsKey(column))
    {
        result = Convert.ChangeType(this._values[column], result.GetType());
        return true;
    }
    return false;
}

このコードを使用してメソッドを呼び出していますが、コンパイラ エラーが発生します。

int age;
a.GetValue("age", out age as object) 

ref または out 引数は割り当て可能な変数でなければなりません

他の誰かがこの問題を抱えていますか、それとも私が何か間違ったことをしているだけですか?

4

3 に答える 3

12

変数は、メソッド シグネチャで指定された型である必要があります。通話中にキャストすることはできません。

age as objectは格納場所ではなく式であるため、割り当て可能な値ではありません。たとえば、割り当ての左手では使用できません。

age as object = 5; // error

キャストを避けたい場合は、一般的な方法を試すことができます。

public bool GetValue<T>(string column, out T result)
{
    result = default(T);
    // values is a Dictionary<string, object>
    if (this._values.ContainsKey(column))
    {
        result = (T)Convert.ChangeType(this._values[column], typeof(T));
        return true;
    }
    return false;
}

もちろん、必要に応じて何らかのエラー チェックを挿入する必要があります)。

于 2012-09-19T09:19:59.273 に答える
2

これを試して

public bool GetValue<T>(string column, out T result)
{
    result = default(T);
    // values is a Dictionary<string, object>
    if (this._values.ContainsKey(column))
    {
        result = (T)Convert.ChangeType(this._values[column], typeof(T));
        return true;
    }
    return false;
}

呼び出しの例

int age;
a.GetValue<int>("age", out age);
于 2012-09-19T09:58:33.250 に答える
0

これを試して

object age; 
a.GetValue("age", out age);

int iage = (int)age;
于 2012-09-19T09:21:24.227 に答える