简体   繁体   English

将值分配给结构值类型

[英]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; 例如,假设我决定Bool也应该有一个FileNotFound值(作为一个愚蠢的例子!),所以我创建了一个结构来包含该值-要在代码中将其用作普通结构,将需要什么?分配给它),如bool b = true; or b = FileNotFound; 或b = FileNotFound;

The Bool is a struct, right? 布尔是一个结构,对吗? And you can do it with the other built-ins: int i = 32; 您可以使用其他内置函数执行此操作:int i = 32; or byte b = 123; 或字节b = 123;

I want to do my own! 我要自己做! Anyone got any ideas...? 任何人有任何想法...?

Cheers - Richard 干杯-理查德

What you want is an enum : see here . 您想要的是一个enum请参见此处

enum 's are sets of values that can be used as types. enum是可以用作类型的值的集合。

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 如果需要方法,请使用structenum请参见此处

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). 仅当声明新实例时(或使用其他方法使用该struct时),该structValues才可用。

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. 您可能希望将struct中的value变量初始化为某种形式,因为该struct的构造struct仍然可以在没有值的情况下调用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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