1

Say, in C++, the following code is legal and widely used:

ObjectType myObject = ObjectType(vector3(10, 9, 3), vector3(40, 0, 0), vector3());

I use constructors passed as arguments to a constructor to avoid having to create a bunch of temporary variables I'll throw away later.

If I try this in C#, like thus:

ObjectType myObject = new ObjectType(vector3(10, 9, 3), vector3(40, 0, 0), vector3());

I get the compiler error

error CS0118: 'myObject' is a 'type' but is used like a 'variable'

Am I making a fundamental error in how I use C#, or is there some workaround I can do?

(Assume that the vector3 class has a default constructor that accepts no arguments, and a constructor that accepts three integers)

4

1 回答 1

3

我使用构造函数作为参数传递给构造函数,以避免创建一堆我稍后会丢弃的临时变量。

您不是在创建和传递临时对象,

在创建对象时使用new关键字,例如:

ObjectType myObject = new ObjectType(new vector3(10, 9, 3), new vector3(40, 0, 0), new vector3());
                                   //^^^^
于 2013-08-27T14:22:29.537 回答