简体   繁体   中英

Assign a value to a struct value-type

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 that - 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.

通常,您不能在C#中执行这种操作。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM