2012-09-19 64 views
5

我在调用我所做的方法时遇到问题。输出参数时出错

的方法我打电话来是folows

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; 
} 

我caling方法与此代码,但我得到一个编译器错误

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

ref或out参数必须是一个可分配的变量

是否有其他人有这个问题,或者我只是做有什么问题?

+0

+1的确是一个很好的问题 – V4Vendetta

回答

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; 
} 

当然,有些错误检查应插入适当的地方)

+0

这正是我一直在寻找:d TX人。 – Bobo

0

试试这个

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

int iage = (int)age; 
+2

你不应该使用匈牙利符号。更好的名字将会是'object tmp'和'int age'。 –

+0

@Justin我想获得真正的类型(int/string/bool/enz)而不必强制类型 – Bobo

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);