改变传递的论点

时间:2018-02-02 17:37:05

标签: 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)
    {
        i.Value = false;   // this should change form_1_Enabled
    }
}

所以,想法是改变传递的属性。 有可能吗?

我发现的唯一解决方案是:

(dynamic)this.GetType().GetProperty(i.Value).GetValue(this, null) = false;

2 个答案:

答案 0 :(得分:1)

只要您必须复制并维护重复状态,您就应该考虑另一种解决方案。保持状态同步是昂贵且容易出错的。

一些替代方案(无特定顺序)

使用字典并直接或间接地拥有其他代码访问权限(通过间接我的意思是你可以有一个帮助函数,它返回一个基于某个参数的值)。

似乎您的代码仅使用字典循环访问私有变量并设置其值。而不是字典使用实例上的反射来查找boolean类型的所有私有字段实例,并根据需要进行额外的检查,如名称或属性标记,并(重新)设置该方式的值。

示例:

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);
    }
}

答案 1 :(得分:1)

因为在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; }
    }
}