我想写一个具有可选参数的方法。它应该更新一些对象,只保留那些给予它的参数,而保持其他属性不变。只有可选参数的方法只能用于设置参数
有问题的部分:
- 空是所有对象的属性
- 对象属性的值不能读取
比较有效的价值究竟应该的签名方法是什么,该方法的逻辑是什么?
因此,可以说物体看起来是这样的:
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;
}
}
如果'null'是一个有效值,则需要用bool指示它应该被写入的每个值,比如'new UpdateableProp {Name =“optBool”,Value = null}'。或者为每个参数添加一个bool参数,表示相同。 –
CodeCaster
您可以使用['[Flags]'](https://stackoverflow.com/q/8447/1997232)类型的枚举的单个属性* code *哪些属性必须被序列化。 – Sinatr