2

不知道如何处理标题,但是当我尝试在列表中投射一个对象时,我得到了那个错误。

这就是我尝试的:

(type)objectList[i] = typeValue;

我希望这会起作用,但事实并非如此。我可以在重写它方面获得一些帮助吗?

4

3 回答 3

2

C# 中的=符号是赋值运算符。它将等号右侧的值分配给左侧的变量。

你有你的陈述倒退

您可以分配 给这样objectList[i]的值typeValue

objectList[i] = typeValue;

如果objectList是类型数组type并且typeValue已经是类型变量,type则不需要强制转换。

如果typeValue不是类型,type那么你可以像这样投射它

(type)typeValue

希望能澄清情况

于 2012-06-13T02:29:33.100 回答
1

我不完全确定你的意思,但如果objectList是一个数组 in typeof(object),则不需要强制转换。如果您尝试强制转换typeValue,然后分配它,您将使用:

objectList[i] = (type)typeValue;
于 2012-06-13T02:17:02.490 回答
0

当您将对象转换为不同的类型时,返回值是常量。值必须是变量才能接受赋值。

也就是说,正确的 cast 和 assign 方法是这样的:

FooInstance = (Foo)BarInstance; // this is a correct cast

上面的代码从强制转换中创建了一个 Foo 类型的常量值,然后将其值分配给 FooInstance,它是一个变量。

(Bar)FooInstance = BarInstance; // this will cause a compiler error

如果允许运行此代码,它将尝试将 BarInstance 的值分配给由强制转换创建的 Bar 类型的常量值。由于您不能分配给常量,因此这是一个错误。

FooInstance = FooInstance2; // this works - no cast necessary
FooInstance = (Foo)FooInstance2; // this cast is unnecessary, but won't cause an error
(Foo)FooInstance = FooInstance2; // this will cause a compiler error

即使它们是同一类型,(Foo)FooInstance 也是常量,因此它不能接受 FooInstance2 的值。另一方面,FooInstance 是一个变量,因此它可以接受 Foo 类型的任何值。

于 2012-06-13T02:51:07.173 回答