demand
If there is such a demand, an object Person
property is set within the outsourcing to another class Options
,
And to set the Person
properties of an object, you must pass a Options
instance,
But can not re-set again for each property, located only attribute to modify.
- Code base
public class Options
{
public string Name { get; set; } = "";
public int Age { get; set; } = 0;
public string Gerder { get; set; } = "";
}
public class Person
{
public void SetOptions(Options options)
{
// 思考一下这里的实现方式
}
private Options myOpts = new Options();
}
- Calling code
var p = new Person();
var opts = new Options()
{
Name = "Hepburn",
Age = 18,
Gerder = "Female"
};
p.SetOptions(opts);
/*
* p
* |_Name: Hepburn
* |_Age: 18
* |_Gender: Female
*
p.SetOptions(new Options() { Age = 19 });
* ↓↓↓
*
* p
* |_Name: Hepburn
* |_Age: 19
* |_Gender: Female
*
*/
p.SetOptions(new Options() { Age = 19 });
- The answer district
↓
↓
↓
↓
↓
↓
↓
↓
↓
public void SetOptions(Options options)
{
foreach (var p in options.GetType().GetProperties())
{
if(!p.CanWrite) continue;
var value = p.GetValue(options);
var valDefault = p.GetValue(new Options());
if(value != valDefault)
{
p.SetValue(myOpts, value);
}
}
}
Thus, when no value is specified will be provided on the same time, requiring the default value is meaningless, for example -1 (minus one), null, etc., because, after once set, by this method no longer change do not return to the default value.