【问题标题】:C# Cannot convert from 'ref xxx' to 'ref object'C# 无法从 'ref xxx' 转换为 'ref object'
【发布时间】:2015-08-08 03:56:18
【问题描述】:

我定义了一个使用 ref 对象作为参数的方法。当我尝试使用 ref List 调用它时,它告诉我无法从 ref List 转换为 ref 对象。 我做了很多搜索以找到答案。然而,大多数答案是“你不需要在这里参考”或者有解决方法。

似乎没有办法从“ref [Inherited]”转换为“ref [Base]”,即使使用 ref (Base)[Inherited]。不知道我说的对不对。

我想要的是在 set { } 块中只写 1 行来更改值并发送通知。有什么建议么?

class CommonFunctions
{
    public static void SetPropertyWithNotification(ref object OriginalValue, object NewValue, ...)
    {
        if(OriginalValue!= NewValue)
        {
            OriginalValue = NewValue;
            //Do stuff to notify property changed                
        }
    }
}
public class MyClass : INotifyPropertyChanged
{
    private List<string> _strList = new List<string>();
    public List<string> StrList
    {
        get { return _strList; }
        set { CommonFunctions.SetPropertyWithNotification(ref _strList, value, ...);};
    }
}

【问题讨论】:

    标签: c# inotifypropertychanged ref


    【解决方案1】:

    使用泛型和 Equals 方法

    class CommonFunctions
    {
        public static void SetPropertyWithNotification<T>(ref T OriginalValue, T NewValue)
        {
            if (!OriginalValue.Equals(NewValue))
            {
                OriginalValue = NewValue;
                //Do stuff to notify property changed                
            }
        }
    }
    public class MyClass
    {
        private List<string> _strList = new List<string>();
        public List<string> StrList
        {
            get { return _strList; }
            set { CommonFunctions.SetPropertyWithNotification(ref _strList, value); }
        }
    }
    

    【讨论】:

    • 另一个问题是要确保什么。从 ref[Inherited] 转换为 ref[Base] 总是非法的吗?
    • @Wenpeng 不,是因为ref 关键字。因为您可以为 ref 参数分配新值,并且它必须与初始参数类型匹配
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多