C# 更改传递参数

C# 更改传递参数,c#,C#,我有这样一个场景: private bool form_1_Enabled = true; private new Dictionary<string,bool> dict = new Dictionary<string,bool>() { { 'is_form_1_enabled', this.form_1_Enabled } }; for(var i in dict) { if (i.Value == true) {

我有这样一个场景:

private bool form_1_Enabled = true;

private new Dictionary<string,bool> dict = new Dictionary<string,bool>()
{
   { 'is_form_1_enabled',  this.form_1_Enabled }
};    

for(var i in dict)
{
    if (i.Value == true)
    {
        i.Value = false;   // this should change form_1_Enabled
    }
}

一旦您必须复制并维护复制状态,您就应该考虑另一种解决方案。保持状态同步既昂贵又容易出错

一些备选方案(无特定顺序)

使用字典并直接或间接地访问其他代码(间接的意思是您可以有一个基于某个参数返回值的helper函数)


代码似乎只使用字典循环私有变量并设置它们的值。使用实例上的反射来查找布尔类型的所有私有字段实例,并根据需要对名称或属性标记进行额外检查,然后(重新)以这种方式设置值,而不是使用字典

例如:

using System.Linq;
using System.Reflection;


public void Reset()
{
    foreach (var field in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
        .Where(x=>x.Name.EndsWith("Enabled", StringComparison.OrdinalIgnoreCase) && x.FieldType == typeof(bool)))
    {
        field.SetValue(this, false);
    }
}
因为在c#中bool是一种值类型,它总是按值复制。如果要通过引用复制它,可以为值类型编写包装器

class A
{
    private BoolWrapper form_1_Enabled = new BoolWrapper(true);

    private new Dictionary<string, BoolWrapper> dict;
    public A()
    {
        dict = new Dictionary<string, BoolWrapper>() { { "is_form_1_enabled", form_1_Enabled }, };
        foreach (var i in dict)
        {
            if (i.Value.Value == true)
            {
                i.Value.Value = false;
            }
        }
    }

    public class BoolWrapper
    {
        public bool Value { get; set; }
        public BoolWrapper(bool value) { this.Value = value; }
    }
}
A类
{
私有BoolWrapper form_1_Enabled=新BoolWrapper(true);
私人新词典;
公共A()
{
dict=newdictionary(){{“是形式1启用的”,形式1启用的},};
foreach(dict中的var i)
{
如果(i.Value.Value==true)
{
i、 Value.Value=false;
}
}
}
公共级说唱歌手
{
公共布尔值{get;set;}
公共BoolWrapper(bool值){this.value=value;}
}
}

What's
i.Value==false应该怎么做?请注意,在c中没有什么比“全局变量”更好的了。您是否希望更改
i.Value
change
form\u 1也能启用
?您在代码注释中所说的
这个
是什么意思?是否只想为布尔值指定不同的值,即:
i.value=false
(注意=用于赋值,==是相等检查)。您需要使用反射或使用
操作或
委托添加自定义回调。也就是说,一旦您必须复制和维护复制状态,您应该考虑不同的解决方案。保持状态同步既昂贵又容易出错。更好的解决方案可能是只使用字典,并直接或间接地访问其他代码(间接的意思是您可以有一个基于某个参数返回值的helper函数)。
class A
{
    private BoolWrapper form_1_Enabled = new BoolWrapper(true);

    private new Dictionary<string, BoolWrapper> dict;
    public A()
    {
        dict = new Dictionary<string, BoolWrapper>() { { "is_form_1_enabled", form_1_Enabled }, };
        foreach (var i in dict)
        {
            if (i.Value.Value == true)
            {
                i.Value.Value = false;
            }
        }
    }

    public class BoolWrapper
    {
        public bool Value { get; set; }
        public BoolWrapper(bool value) { this.Value = value; }
    }
}