I want to be able to create a struct, and use it like a normal built-in. For example, say I decide that the Bool should also have a FileNotFound value (as a silly example!), so I create a struct to include 开发者_StackOverflowthat - what would it take to be able to use it as a normal struct in code (ie. assign to it), as in bool b = true; or b = FileNotFound;
The Bool is a struct, right? And you can do it with the other built-ins: int i = 32; or byte b = 123;
I want to do my own! Anyone got any ideas...?
Cheers - Richard
What you want is an enum
: see here.
enum
's are sets of values that can be used as types.
So you can do:
enum MyBool {True=1, False, FileNotFound};
MyBool b = MyBool.FileNotFound;
If you want methods, use a struct
and an enum
: see here
public struct MyBool
{
internal enum Values {True=1, False, FileNotFound};
Values value;
public MyBool(Values v)
{
value = v;
}
}
MyBool b = new MyBool(MyBool.Values.FileNotFound);
The Values
of the struct
will only be available to it when declaring a new instance (or if you make any other methods that use it).
You probably want to initialize the value
variable in the struct to something, because the constructor for the struct
can still be called without a value.
You cannot, in general, do this sort of thing in C#.
精彩评论