2017-07-31 25 views
1

我想寫一個具有可選參數的方法。它應該更新一些對象,只保留那些給予它的參數,而保持其他屬性不變。只有可選參數的方法只能用於設置參數

有問題的部分:

  • 空是所有對象的屬性
  • 對象屬性的值不能讀取

比較有效的價值究竟應該的簽名方法是什麼,該方法的邏輯是什麼?

因此,可以說物體看起來是這樣的:

public class Foo 
{ 
    public int Id { get; set; } 
    public bool? MyBool { get; set; } 
    public int? MyInt { get; set; } 
    public string MyString { get; set; } 
} 

而且可以說,該方法是這樣的:

public void UpdateObject(int id, bool? optBool = null, int? optInt = null, 
          string optString = null) 
{ 
    var objectToUpdate = _fooList.FirstOrDefault(x => x.Id = id); 

    if(objectToUpdate != null) 
    { 
     // Update only set properties? 
    } 
} 

現在,我想調用該方法來更新不同部分的屬性我的申請是這樣的:

// at some part of app 
UpdateObject(1, optInt: 5); 
// will set the int property to 5 and leaves other properties unchanged 

// at other part of app 
UpdateObject(1, optString: "lorem ipsum"); 
// will set the string property and leaves other properties unchanged 

// at other part of app 
UpdateObject(1, optBool: null, optString: "lorem ipsum"); 
// will set the string and bool property and leaves other properties unchanged 

請注意,只是設置值將不起作用,因爲它會覆蓋不需要的屬性爲空。

public void UpdateObject(int id, bool? optBool = null, int? optInt = null, 
          string optString = null) 
{ 
    var objectToUpdate = _fooList.FirstOrDefault(x => x.Id = id); 

    if(objectToUpdate != null) 
    { 
     // This is wrong 
     objectToUpdate.MyBool = optBool; 
     objectToUpdate.MyInt = optInt; 
     objectToUpdate.MyString = optString; 
    } 
} 
+4

如果'null'是一個有效值,則需要用bool指示它應該被寫入的每個值,比如'new UpdateableProp {Name =「optBool」,Value = null}'。或者爲每個參數添加一個bool參數,表示相同。 – CodeCaster

+0

您可以使用['[Flags]'](https://stackoverflow.com/q/8447/1997232)類型的枚舉的單個屬性* code *哪些屬性必須被序列化。 – Sinatr

回答

3

而不是傳入新的值。傳入提供新值的Func<T>。如果Func爲空,那麼你什麼都不做。如果Func返回null,則只將該值設置爲null。

public void UpdateObject(Func<int> idProvider, Func<bool?> optBoolProvider = null, Func<int?> optIntProvider = null, 
          Func<string> optStringProvider = null) 
{ 
    if(idProvider != null) Id = idProvider(); // etc. 
} 

而你把它想:

UpdateObject(() => 1234,() => null, optStringProvider:() => "hello world"); 

的選擇,如果你可以讀取電流值,是與一個Func<T,T>而不是默認爲null你默認的身份,即X - > x。然後,你不需要做空校驗(除如果必須在合同)

public void UpdateObject(Func<int,int> idProvider, Func<bool?,bool?> optBoolProvider = x => x, Func<int?> optIntProvider = x => x, 
           Func<string> optStringProvider = x => x) 
    { 
     Id = idProvider(Id); // etc. 
    } 

我一直在Java土地最近,所以道歉,如果語法是關閉的。

0

你可以重載函數,給你選擇添加哪些變量以及保持相同。

這樣,您可以選擇只更改要更改的給定對象的值。

你也可以做到以下幾點:

public Foo changeString(Foo f, string s) 
{ 
    f.myString = s; 
    return f; 
} 
public Foo changeInt(Foo f, int i) 
{ 
    f.myInt = i; 
    return f; 
} 

//external piece of code 
Foo f = new Foo(); 
f = changeInt(f, 5).changeString(f, "abc"); 

這將鏈中的功能和不接觸任何其他編輯這兩個屬性。也許這可以幫助你解決你的問題。

+0

建模者,好主意!但我真的正在尋找一種方法來保持更新邏輯的一種方法。 –