问题描述
来自文档:
与类不同,结构体可以在不使用 new 运算符的情况下进行实例化.
那为什么我会收到这个错误:
So why am I getting this error:
使用未赋值的局部变量'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));
这篇关于C# 结构:未分配的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!