开发者

struct - might not be initialized before use

开发者 https://www.devze.com 2023-01-28 04:18 出处:网络
Given the follow contrived struct public struct CarParts { public int trunk; publi开发者_开发知识库c int door;

Given the follow contrived struct

public struct CarParts
{
        public int trunk;
        publi开发者_开发知识库c int door;
}

Why do I get an error that says "cp might not be initialized before use" however if I do the exact same thing in a static method id doesnt work. Also why did it used to comple before I added the static method?

public void Test()
{
            CarParts cp;
            cp.trunk= 1;
            cp.door= 4;
}


I guess that this is relevant to your question:

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

0

精彩评论

暂无评论...
验证码 换一张
取 消