您可以这样定义映射:
Mapping<Foobar, decimal> foobarMapping = new Mapping<Foobar, decimal>
{
{ "one", f => f.One },
{ "double", f => f.Two },
{ "tricycle", f => f.Three },
};
public class Foobar
{
public decimal One { get; set; }
public decimal Two { get; set; }
public decimal Three { get; set; }
}
void Main()
{
Foobar obj = new Foobar();
obj.One = 100M;
foobarMapping[obj, "one"].Dump();
foobarMapping[obj, "tricycle"] = 400M;
obj.Three.Dump();
}
class Mapping<TFrom, TTo>: IEnumerable<KeyValuePair<string, PropertyInfo>>
{
Dictionary<string, PropertyInfo> mapping = new Dictionary<string, PropertyInfo>();
public void Add(string name, Expression<Func<TFrom, TTo>> mappingFunction) =>
mapping.Add(name, (PropertyInfo)((MemberExpression)mappingFunction.Body).Member);
public TTo this[TFrom from, string key]
{
get => (TTo)mapping[key].GetValue(from);
set => mapping[key].SetValue(from, value);
}
public IEnumerator<KeyValuePair<string, PropertyInfo>> GetEnumerator() =>
mapping.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
如预期,哪些产出:
100
400