我有非常简单的结构如下:
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
Run Code Online (Sandbox Code Playgroud)
我已将警告设为错误.现在为所有三个int获得错误
字段永远不会分配给,并且始终具有默认值0
显然,如果我尝试初始化intto,我会收到错误0.有没有办法处理这个没有禁用警告为错误.
您可以像这样为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)
如果你的结构在内部类中,那么你就会得到这个转换
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)
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.