You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#:不使用反射,如何以通用方式传递属性实现跨类同步修改?

解决属性变更时同步设置另一个类属性的问题

问题根源

你的代码无法正常运行的核心原因:

  1. 值类型传递限制:bool是值类型,直接传递MyAnotherClass.AnotherPropertyOne时,传递的是属性的当前值副本,而非属性本身。在SavePropertyToFile中修改局部变量不会影响MyAnotherClass的实际属性。
  2. 泛型方法语法错误:SavePropertyToFile方法的泛型参数TProperty未声明,且即使修正,值类型的传递逻辑也无法实现修改原属性的需求。

解决方案:通过委托传递属性设置逻辑

使用Action<bool>类型的委托,让SavePropertyToFile方法通过委托直接修改MyAnotherClass的对应属性,代码简洁且易扩展。

修改后的完整代码:

class MyClassOne
{
    private bool _propertyOne;
    private bool _propertyTwo;
    private bool _propertyThree;

    public bool PropertyOne
    {
        get => _propertyOne;
        set
        {
            if (_propertyOne == value)
                return;

            _propertyOne = value;
            SavePropertyToFile(value, val => MyAnotherClass.AnotherPropertyOne = val);
            NotifyOfPropertyChange(() => PropertyOne);
        }
    }

    public bool PropertyTwo
    {
        get => _propertyTwo;
        set
        {
            if (_propertyTwo == value)
                return;

            _propertyTwo = value;
            SavePropertyToFile(value, val => MyAnotherClass.AnotherPropertyTwo = val);
            NotifyOfPropertyChange(() => PropertyTwo);
        }
    }

    public bool PropertyThree
    {
        get => _propertyThree;
        set
        {
            if (_propertyThree == value)
                return;

            _propertyThree = value;
            SavePropertyToFile(value, val => MyAnotherClass.AnotherPropertyThree = val);
            NotifyOfPropertyChange(() => PropertyThree);
        }
    }

    private void SavePropertyToFile(bool value, Action<bool> setTargetProperty)
    {
        // 通过委托设置目标类的属性
        setTargetProperty(value);
        
        // 原有业务逻辑
        RefreshProgram();
    }

    // 以下为假设的辅助方法实现
    private void NotifyOfPropertyChange<T>(Expression<Func<T>> propertyExpression)
    {
        // 实现属性变更通知逻辑
    }

    private void RefreshProgram()
    {
        // 实现程序刷新逻辑
    }
}

// 假设的目标类定义
static class MyAnotherClass
{
    public static bool AnotherPropertyOne { get; set; }
    public static bool AnotherPropertyTwo { get; set; }
    public static bool AnotherPropertyThree { get; set; }
}

关键说明

  • 委托的作用:Action<bool>是无返回值的委托,接收一个bool参数。在调用SavePropertyToFile时,传入的lambda表达式val => MyAnotherClass.AnotherPropertyX = val直接定义了如何设置目标属性。
  • 扩展性:未来新增属性时,只需要在新属性的setter中复用相同的委托传递逻辑即可,无需修改SavePropertyToFile方法的核心代码。
  • 实例类适配:如果MyAnotherClass是实例类而非静态类,只需将委托中的MyAnotherClass替换为类的实例对象(比如_anotherClassInstance)即可。

内容的提问来源于stack exchange,提问作者skm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:05:39