首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#不能从“ref”转换为“ref对象”

C#不能从“ref”转换为“ref对象”
EN

Stack Overflow用户
提问于 2015-08-08 03:56:18
回答 1查看 3K关注 0票数 5

我使用ref对象作为参数定义了一个方法。当我尝试用ref列表调用它时,它告诉我不能从ref列表转换为ref对象。为了找到答案,我做了很多搜索。然而,大多数的答案都是“您不需要这里的参考”或有工作周围。

即使使用继承的ref (Base),似乎也无法从“ref继承”转换为“ref Base”。不知道我说得对不对。

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

代码语言:javascript
复制
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, ...);};
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-08 03:58:56

使用泛型和等号方法

代码语言:javascript
复制
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); }
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31889481

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档