您可以编写一个使用反射的属性包装类,如下所示:
public class PropertyWrapper<T>
{
readonly PropertyInfo property;
readonly object obj;
public PropertyWrapper(object obj, string propertyName)
{
property = obj.GetType().GetProperty(propertyName);
this.obj = obj;
}
public T Value
{
get
{
return (T)property.GetValue(obj);
}
set
{
property.SetValue(obj, value);
}
}
}
然后你可以像这样使用它:
public class Test
{
public string Item { get; set; }
}
class Program
{
void run()
{
Test test = new Test { Item = "Initial Item" };
Console.WriteLine(test.Item); // Prints "Initial Item"
var wrapper = new PropertyWrapper<string>(test, "Item");
Console.WriteLine(wrapper.Value); // Prints "Initial Item"
wrapper.Value = "Changed Item";
Console.WriteLine(wrapper.Value); // Prints "Changed Item"
}
static void Main()
{
new Program().run();
}
}
[编辑]我不得不回到这个发布一种没有反思的方式:
public class PropertyWrapper<T>
{
readonly Action<T> set;
readonly Func<T> get;
public PropertyWrapper(Func<T> get, Action<T> set)
{
this.get = get;
this.set = set;
}
public T Value
{
get
{
return get();
}
set
{
set(value);
}
}
}
public class Test
{
public string Item
{
get;
set;
}
}
class Program
{
void run()
{
Test test = new Test
{
Item = "Initial Item"
};
Console.WriteLine(test.Item); // Prints "Initial Item"
var wrapper = new PropertyWrapper<string>(() => test.Item, value => test.Item = value);
Console.WriteLine(wrapper.Value); // Prints "Initial Item"
wrapper.Value = "Changed Item";
Console.WriteLine(wrapper.Value); // Prints "Changed Item"
}
static void Main()
{
new Program().run();
}
}