繁体   English   中英

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

[英]C# Cannot convert from 'ref xxx' to 'ref object'

我定义了一个使用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, ...);};
    }
}

使用泛型和等于方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM