布尔数据类型存储字符串值

布尔数据类型存储字符串值

问题描述:



在我的senario中,我需要将一些字符串值存储到布尔数据类型变量中。

是否可以在c#中使用?



说明:我将一个变量声明为布尔值。

但是在同样的bool变量我想存储一些字符串数据。

数据类型应该只有布尔值。



问候,

Vasanth

Hi,
In my senario, I need to store some string value into boolean data type variable.
Is it possible in c#?

Explanation: I declare one variable as a Boolean.
But in that same bool variable I want to store some string data.
Datatype should be Boolean only.

Regards,
Vasanth

不,布尔值只存储一个布尔值。但是,您可以创建自己的类型,其中包含您想要的任何类型的数据。



我真的不确定这个请求的有效商业案例,你能告诉我们你想要实现的东西,你需要存储一个字符串吗?一个bool?



这是一个自定义类型的例子:

No, a boolean only stores a boolean. However you can create your own "type" that holds as much data of any kind that you want.

I'm really not sure of a valid business case for this request, can you tell us what you are trying to achieve that you would need to store a string in a bool?

Here is an example of a custom type:
public class CompoundBool
{
    public bool Value { get; set; }
    public string String { get; set; }

    public static implicit operator bool(CompoundBool v)
    {
        return v.Value;
    }

    public static implicit operator CompoundBool(bool b)
    {
        return new CompoundBool() { Value = b };
    }

}





您可以像以下一样使用它:





And you can use it like:

CompoundBool b = new CompoundBool() { Value = true; String = "My String Data" };

bool myBool = b;

//myBool now equals true

//Or....

CompoundBool b = true;
b.String = "My String Data";

bool myBool = b;

//myBool equals true





但我不会这样做,因为它不能有效地使用转换运算符,也不符合良好的编码习惯。



But I would NOT do this, as its not a valid use of conversion operators and does not comply with good coding practices.