[英]Struct in c# giving warning Field is never assigned to,and will always have its default value0
I have very simple struct as below: 我有非常简单的结构如下:
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
I have enabled warning as error . 我已将警告设为错误 。 Now for all three
int
getting error 现在为所有三个
int
获取错误
Field is never assigned to,and will always have its default value 0
字段永远不会分配给,并且始终具有默认值0
Obviously I will get error if I try to initialize the int
to 0
. 显然,如果我尝试将
int
初始化为0
我将收到错误。 Is there any way to handle this without disabling warning as error. 有没有办法处理这个没有禁用警告为错误。
I had been receiving the warning when I copy pasted author's code. 当我复制粘贴的作者代码时,我一直收到警告。
You can define a constructor for the Struct like this 您可以像这样为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;
}
}
You can also use a constructor with just one parameter and initialize all 您也可以使用只有一个参数的构造函数并初始化all
public ShFileInfo(int x)
{
hIcon = x;
iIcon = 0;
dwAttributes = 0;
}
If your struct is inside internal class then you get this warrning 如果你的结构在内部类中,那么你就会得到这个转换
internal class WrapperClass
{
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
}
when you change internal access to public then warnings gone: 当您将内部访问权限更改为public时,警告就会消失:
public class WrapperClass
{
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
}
Since you are using this structure for P/Invoke only, I'd simply disable the warning locally: 由于您仅将此结构用于P / Invoke,因此我只需在本地禁用警告:
#pragma warning disable 0649
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
#pragma warning restore 0649
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. 编译器无法知道您的结构是在非托管代码中分配的,但是因为您知道,简单地禁用警告几乎没有什么坏处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.