C#无法从'ref xxx'转换为'ref object'

时间:2015-08-08 03:56:18

标签: c# inotifypropertychanged ref

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

似乎无法将'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, ...);};
    }
}

1 个答案:

答案 0 :(得分:1)

使用泛型和等于方法

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); }
    }
}
相关问题