Я не горжусь этим:
public abstract class HorribleBaseType
{
private Lazy<string> _connectionString;
private Action<string> _connectionStringSetter;
private Func<string> _connectionStringGetter;
public HorribleBaseType(
Func<string> connectionStringGetter,
Action<string> connectionStringSetter)
{
_connectionStringGetter = connectionStringGetter;
_connectionStringSetter = connectionStringSetter;
_connectionString = new Lazy<string>(connectionStringGetter);
}
public string ConnectionString
{
get { return _connectionString.Value; }
set
{
_connectionStringSetter(value);
_connectionString = new Lazy<string>(_connectionStringGetter);
}
}
}
public class HorribleType : HorribleBaseType
{
public HorribleType()
: base(() => MyConfiguration.ConnectionString,
(v) => MyConfiguration.ConnectionString = v) { }
}
100% не проверено.
ОБНОВЛЕНИЕ Используя комбинацию вышеупомянутого и ответ @ охотника, выможет сделать что-то вроде:
public class DelegateProperty<T>
{
#region Fields
private readonly Func<T> _getter;
private readonly Action<T> _setter;
private Lazy<T> _lazy;
#endregion
#region Constructors
public DelegateProperty(Func<T> getter, Action<T> setter)
{
_getter = getter;
_setter = setter;
_lazy = new Lazy<T>(getter);
}
#endregion
#region Properties
public T Value
{
get { return _lazy.Value; }
set
{
_setter(value);
_lazy = new Lazy<T>(_getter);
}
}
#endregion
#region Operators
public static implicit operator T(DelegateProperty<T> prop)
{
return prop.Value;
}
#endregion
}
Теперь вы можете сделать что-то вроде:
class Program
{
static void Main(string[] args)
{
string name = "Matt";
var prop = new DelegateProperty<string>(
() => name,
value => name = value);
var test = new Test(prop);
Console.WriteLine(test.Name);
test.Name = "Ben";
Console.WriteLine(name);
Console.ReadKey();
}
}
public class Test
{
private readonly DelegateProperty<string> NameProperty;
public Test(DelegateProperty<string> prop)
{
NameProperty = prop;
}
public string Name
{
get { return NameProperty; }
set { NameProperty.Value = value; }
}
}