2015-08-08 110 views
0

我定義了一個使用ref對象作爲參數的方法。當我嘗試用ref List調用它時,它告訴我不能從ref List轉換爲ref對象。 我已經做了很多搜索來找到答案。然而,大多數答案是「你不需要在這裏工作」或者有解決方法。C#無法從'ref xxx'轉換爲'ref object'

似乎沒有辦法從'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, ...);}; 
    } 
} 

回答

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

謝謝後背!有用。 – Wenpeng

+0

@Wenpeng歡迎您,您可以打勾我的答案。 – Backs

+0

另一個問題要確定。從ref [Inherited]轉換爲ref [Base]是否總是非法的? – Wenpeng