c#中给出警告的结构字段永远不会分配给,并且始终具有默认值0

Shr*_*abh 3 c#

我有非常简单的结构如下:

 public struct ShFileInfo
 {
     public int hIcon;
     public int iIcon;
     public int dwAttributes;
 }
Run Code Online (Sandbox Code Playgroud)

我已将警告设为错误.现在为所有三个int获得错误

字段永远不会分配给,并且始终具有默认值0

显然,如果我尝试初始化intto,我会收到错误0.有没有办法处理这个没有禁用警告为错误.

win*_*der 5

当我复制粘贴的作者代码时,我一直收到警告. 收到警告

您可以像这样为Struct定义构造函数

public struct ShFileInfo
    {
        public int hIcon;
        public int iIcon;
        public int dwAttributes;

        public ShFileInfo(int x,int y, int z)
        {
            hIcon = x;
            iIcon = y;
            dwAttributes = z;
        }
    }
Run Code Online (Sandbox Code Playgroud)

您也可以使用只有一个参数的构造函数并初始化all

  public ShFileInfo(int x)
        {
            hIcon = x;
            iIcon = 0;
            dwAttributes = 0;
        }
Run Code Online (Sandbox Code Playgroud)

  • 我是堆叠溢出的新手,所以有人会在做这个之前留下评论说明投票的原因,这样我就不会再犯同样的错误 (3认同)
  • 这并没有解决为什么作者首先看到此警告消息的问题...我只是将粘贴的 autohrs 代码复制到 Visual Studio,但无法重现此问题。如果您也回答这个问题,我会将我的反对票改为赞成票。 (2认同)

Pio*_*eka 5

如果你的结构在内部类中,那么你就会得到这个转换

internal class WrapperClass
{
    public struct ShFileInfo
    {
        public int hIcon;
        public int iIcon;
        public int dwAttributes;
    }
}   
Run Code Online (Sandbox Code Playgroud)

当您将内部访问权限更改为public时,警告就会消失:

public class WrapperClass
{
    public struct ShFileInfo
    {
        public int hIcon;
        public int iIcon;
        public int dwAttributes;
    }
}
Run Code Online (Sandbox Code Playgroud)


Lua*_*aan 5

Since you are using this structure for P/Invoke only, I'd simply disable the warning locally:

#pragma warning disable 0649
public struct ShFileInfo
{
    public int hIcon;
    public int iIcon;
    public int dwAttributes;
}
#pragma warning restore 0649
Run Code Online (Sandbox Code Playgroud)

The compiler has no way of knowing that your structure is assigned in the unmanaged code, but since you know, there's little hurt in simply disabling the warning.