Using c# I would like to set the variables within a struct which is a member of a class, from within that class. Pretty new to c#. Help appreciated.
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();
}
}
Error: 'An object reference is required for the non-static field, method, or property myclass.mystruct.something'
mystruct
is a type within class, but you do not have any field with that type:
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();
}
}
There is a difference between struct definition and struct instance. You need to instantiate mystruct first, then you can assign value to it - either that or declaring the mystruct something as static field.
public struct mystruct
{
public int something;
}
var foo = new mystruct();
foo.something = 20;
or
public struct mystruct
{
public static int something;
}
mystruct.something = 20;
You should create an object for mystruct
public void init()
{
mystruct m = new mystruct();
m.something = 20;
}
public struct mystruct
{
public int something;
}
This is just a definition. As the error states, you must have an initialized object to use instance variables.
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;
}
Wow, this is amazing!
I would have bet that most if not all would point out that you are not only confusing Type with Instance but also not using Struct in the recommended way..
You should use structs only as immutables, meaning that you should make all members readonly
and set them only in the constructor!
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();
}
}
If you need read-write acces to the members you should not use struct but class!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.