C#结构体:未分配的本地变量?
从文档:
不同于类,结构可以不使用new运算符实例化。
Unlike classes, structs can be instantiated without using a new operator.
那么,为什么我收到这个错误:
So why am I getting this error:
未分配的局部变量的使用X
Use of unassigned local variable 'x'
当我尝试这样做。
Vec2 x;
x.X = det * (a22 * b.X - a12 * b.Y);
x.Y = det * (a11 * b.Y - a21 * b.X);
其中, VEC2 X
是一个结构?
那么,X和Y属性(而不是字段)?如果是这样,这就是问题所在。直到在所有字段X
肯定是分配的,你不能调用任何方法或属性。
Well, are X and Y properties (rather than fields)? If so, that's the problem. Until all the fields within x
are definitely assigned, you can't call any methods or properties.
有关实例
public struct Foo
{
public int x;
public int X { get { return x; } set { x = value; } }
}
class Program
{
static void Main(string[] args)
{
Foo a;
a.x = 10; // Valid
Foo b;
b.X = 10; // Invalid
}
}
是 VEC2
您自己的类型?你可以访问所涉及的领域,或仅属性?
Is Vec2
your own type? Do you have access to the fields involved, or only the properties?
如果这是你自己的类型,我会的强烈的敦促你尝试坚持不变的结构。我知道托管DirectX具有越来越接近尽可能最佳性能的一些可变的结构,但是这是在陌生的情况下,这样的成本 - 和差很多,说实话
If it's your own type, I would strongly urge you to try to stick to immutable structs. I know managed DirectX has some mutable structs for getting as close to optimal performance as possible, but that's at the cost of strange situations like this - and much worse, to be honest.
我会亲自给该结构的构造以X和Y:
I would personally give the struct a constructor taking X and Y:
Vec2 x = new Vec2(det * (a22 * b.X - a12 * b.Y),
det * (a11 * b.Y - a21 * b.X));