Reputation: 2987
I am having a piece of code in which i delegate certain properties of a class to another class if the class exists. Below you see the start time being defined on the TimeProvider if it exists.
public override DateTime StartTime
{
get
{
return (TimeProvider != null) ? TimeProvider.StartTime : base.StartTime;
}
set
{
if (TimeProvider != null)
{
TimeProvider.StartTime = value;
}
else
{
base.StartTime = value;
}
}
}
Now my 'problem' is that i have a lot more properties (like endtime,currentime) i delegate to the TimeProvider if it is not null. So i would like to have code like:
public override DateTime StartTime
{
get
{
return GetTime(()=>StartTime);
}
set
{
SetTime(()=>StartTime)
}
}
Where the ()=>StartTime expression is sometimes 'evaluated' on the TimeProvider and sometimes on the class itself (they share a baseclass). Can something like this be done? Preferably without using reflection.
Upvotes: 2
Views: 93
Reputation: 3242
Cake
public class Foo
{
private string _string1;
public Foo foo { get; set; }
private T GetProperty<T>(Func<Foo,T> getter)
{
return foo == null
? getter(this)
: getter(foo);
}
private void SetProperty(Action<Foo> setter)
{
if (foo == null)
setter(this);
else
setter(foo);
}
public string String1
{
get { return GetProperty(a => a._string1); }
set { SetProperty(a => a._string1 = value); }
}
}
Upvotes: 1