我在这里遇到了瓶颈。是否可以将一个bool复制到另一个的引用中?考虑以下代码...
bool a = false;
bool b = a;
b现在是一个完全独立的布尔型变量,值为false。如果我随后改变a,这不会影响到b。是否可能通过引用使a=b?我该如何做到这一点?非常感谢。
我在这里遇到了瓶颈。是否可以将一个bool复制到另一个的引用中?考虑以下代码...
bool a = false;
bool b = a;
b现在是一个完全独立的布尔型变量,值为false。如果我随后改变a,这不会影响到b。是否可能通过引用使a=b?我该如何做到这一点?不会。因为bool是一个值类型,它总是被按值复制。
最好的选择是将您的bool包装在一个类中 - 这将给它引用类型语义:
public class BoolWrapper
{
public bool Value { get; set; }
public BoolWrapper (bool value) { this.Value = value; }
}
BoolWrapper a = new BoolWrapper(false);
BoolWrapper b = a;
b.Value = true;
// a.Value == true
感谢@Reed的回答(+1)!他鼓励我提出更加“通用”的解决方案! :)
public class ValueWrapper<T> where T : struct
{
public T Value { get; set; }
public ValueWrapper(T value) { this.Value = value; }
}
Value
设为属性而不是字段?可以在字段上使用 Interlocked.CompareExchange
等东西,但不能在属性上使用。也许对于 ValueWrapper<System.Boolean>
不相关,但对于 ValueWrapper<System.Integer>
肯定相关。 - supercat对Andrey的答案进行小扩展...这可以让你直接将其分配给最终想要的任何类型。因此:
ValueWrapper<bool> wrappedBool = new ValueWrapper<bool>(true);
bool unwrapped = wrappedBool; // you can assign it direclty:
if (wrappedBool) { // or use it how you'd use a bool directly
// ...
}
public class ValueWrapper<T>
{
public T Value { get; set; }
public ValueWrapper() { }
public ValueWrapper(T value) {
this.Value = value;
}
public static implicit operator T(ValueWrapper<T> wrapper)
{
if (wrapper == null) {
return default(T);
}
return wrapper.Value;
}
}
这可能不是您想要的,但如果您的情况需要一个函数来修改本地的布尔值,您可以使用 ref 或 out 关键字。
bool a = false;
F(ref a);
// a now equals true
...
void F(ref bool x)
{
x = true;
}
我猜想你需要传递一个 bool 的引用,但是你无法使用“BoolWrapper”类进行包装,因为该 bool 存在于你不能或不想修改的某个位置。
这是可以做到的!
首先声明任何 bool 引用将看起来像什么
/// <summary> A reference to a bool.</summary>
/// <param name="value">new value</param>
/// <returns>Value of boolean</returns>
public delegate bool BoolRef(bool? value = null);
bool myBool; // A given bool that you cannot wrap or change
private bool myBoolRef(bool? value) {
if (value != null) {
myBool = (bool)value;
}
return myBool;
}
void myTestCaller() {
foo(myBoolRef);
}
void foo(BoolRef b) {
bool c = b(); // get myBool
b(true); // set myBool to true
}
同样的技巧也适用于其他值类型,例如int。
public class Class1
{
bool myBool { get; set; }
void changeBoolFunc(bool val) { myBool = val; }
public Class1()
{
Action<bool> changeBoolAction = changeBoolFunc;
myBool = true;
Console.WriteLine(myBool); // outputs "True"
Class2 c2 = new Class2(changeBoolAction);
Console.WriteLine(myBool); // outputs "False"
}
}
public class Class2
{
public Class2(Action<bool> boolChanger) { boolChanger(false); }
}
void Main()
{
Class1 c1 = new Class1();
}
bool 是一个值类型,不能通过引用进行复制。
只需将标志用作Nullable<bool>
或bool?
,并在传递给通用方法的结构中设置这些标志。上面的ValueWrapper<T>
类本质上就是Nullable<T>
所做的。