C# Cannot convert from 'ref xxx' to 'ref object&

本文关键字:ref xxx object to Cannot convert from | 更新日期: 2023-09-27 18:07:01

我定义了一个使用ref object作为参数的方法。当我尝试用ref List调用它时,它告诉我不能从ref List转换为ref object。为了找到答案,我做了大量的研究。然而,大多数答案是"你不需要参考",或者有变通的办法。

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

我想在set{}块中只写一行来改变值并发送通知。有什么建议吗?

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# Cannot convert from 'ref xxx' to 'ref object&

使用泛型和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); }
    }
}