C#不是可以用 as 来转换类型吗,但不能用于KeyValuePair。我有一句是这样的 System.Collections.Generic.KeyValuePair<string, string> specializedData = data as System.Collections.Generic.KeyValuePair<string, string>;编译器返回出错信息  Error 10 The as operator must be used with a reference type or nullable type ('System.Collections.Generic.KeyValuePair<string,string>' is a non-nullable value type) 我的data本来就是这个数据类型的,我应该怎们转换才可以呢。

解决方案 »

  1.   

    我这样写似乎可以 System.Collections.Generic.KeyValuePair<string, string> specializedData = (System.Collections.Generic.KeyValuePair<string, string>)data;请问 as 操作 和  (DataType)xxx 操作有和区别啊?
      

  2.   

    提示非常清楚,你看不懂吗?System.Collections.Generic.KeyValuePair<TKey, TValue>是结构,是值类型...as运算符只可用于引用类型和泛型可空结构...
      

  3.   

    KeyValuePair(TKey, TValue) 结构
    as关键字 
    用于在兼容的引用类型之间执行转换
    as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用强制转换表达式来执行。