2017-07-31 53 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

建模者,好主意!但我真的正在寻找一种方法来保持更新逻辑的一种方法。 –