如何在类中定义结构时初始化结构成员?
使用c#我想在该类中的一个类的成员结构中设置变量。对c#来说很新鲜。帮助赞赏。如何在类中定义结构时初始化结构成员?
class myclass
{
public struct mystruct
{
public int something;
}
public void init()
{
mystruct.something = 20; // <-- this is an error
}
static void Main(string[] args)
{
myclass c = new myclass();
c.init();
}
}
错误:一个对象引用是所必需的非静态字段,方法或属性myclass.mystruct.something'
mystruct
是类中的一个类型,但你没有任何字段与该类型:
class myclass
{
public struct mystruct
{
public int something;
}
private mystruct field;
public void init()
{
field.something = 20; // <-- this is no longer an error :)
}
static void Main(string[] args)
{
myclass c = new myclass();
c.init();
}
}
您应该创建mystruct
public void init()
{
mystruct m = new mystruct();
m.something = 20;
}
考虑增加更多的单词(downvote不是我的btw) – quetzalcoatl 2014-10-30 10:24:25
@quetzalcoatl我想在回答后编辑 – Venkat 2014-10-30 10:29:24
这是否为-1? – Venkat 2014-10-30 10:29:42
public struct mystruct
{
public int something;
}
对象
这只是一个定义。如错误状态,您必须有一个初始化对象才能使用实例变量。
class myclass
{
public struct mystruct
{
public int something;
}
public void init()
{
mystruct haha = new mystruct();
haha.something = 20; // <-- modify the variable of the specific instance
}
static void Main(string[] args)
{
myclass c = new myclass();
c.init();
}
}
class myclass
{
mystruct m_mystruct;
public void init()
{
m_mystruct.something = 20;
}
static void Main(string[] args)
{
myclass c = new myclass();
c.init();
}
}
public struct mystruct
{
public int something;
}
有结构定义和结构实例之间的差异。你需要首先实例化mystruct,然后你可以给它赋值 - 或者将mystruct声明为静态字段。
public struct mystruct
{
public int something;
}
var foo = new mystruct();
foo.something = 20;
或
public struct mystruct
{
public static int something;
}
mystruct.something = 20;
哇,这是惊人的!
我会打赌,如果不是所有想指出,你不仅混淆类型与实例,但也没有在推荐的方法使用结构..
你应该用结构仅作为immutables,这意味着你应该让所有成员readonly
并只在构造函数中设置它们!
class myclass
{
mystruct oneMyStruct;
public struct mystruct
{
public readonly int something;
public mystruct(int something_) { something = something_; }
}
public void init()
{
oneMyStruct = new mystruct(20);
}
static void Main(string[] args)
{
myclass c = new myclass();
c.init();
}
}
如果您需要对成员进行读写访问,您不应该使用struct而是class!
您确定这是所有的代码?这会导致编译器错误,没有运行时错误。如果你有一个字段'mystruct mystruct',这个错误不会发生,因为它将被初始化。请显示实际的代码。 – CodeCaster 2014-10-30 10:22:52
'mystruct'是一种类型,而不是该类型的字段。 – 2014-10-30 10:23:17
您已经定义了一个结构,但没有定义该结构的一个实例。 – DavidG 2014-10-30 10:23:22