Cast on a "float" sequence throws InvalidCastException

原因 :The Cast method only supports reference and boxing conversions. Use Select instead:

就是说cast<>()方法只支持装箱和拆箱操作,其他强制类型转换不支持。

比如:你要完成以下代码,会抛出异常的:

static void Main(string[] args)
{
Hashtable st
= new Hashtable();
st.Add(
"a",12);
st.Add(
"b",13);
st.Add(
"c", 14);
double sum = st.Values.Cast<float>().Sum();
}

而这样是可以的:

Hashtable st = new Hashtable();
st.Add(
"a",12f);
st.Add(
"b",13f);
st.Add(
"c", 14f);
double sum = st.Values.Cast<float>().Sum();

posted @ 2011-04-28 15:12  kntao  阅读(191)  评论(0编辑  收藏  举报