我有一个类叫做 MapBuilder<T>内部使用 Dictionary<PropertyInfo,string> 该类用于快速建立将代理哪些属性的映射。 该类看起来像这样::
public class MapBuilder<T>{
private Dictionary<PropertyInfo, string> m_Map = new Dictionary<PropertyInfo,string>();
public MapBuilder<T> Add<TProperty>(Expression<Func<T, TProperty>> property){
ArgumentValidator.AssertIsNotNull(()=>property);
var propertyInfo = Reflect.Property<T>.InfoOf(property);
m_Map.Add(propertyInfo, propertyInfo.Name);
return this;
}
public MapBuilder<T> Add<TProperty>(Expression<Func<T, TProperty>> property,string columnName){
ArgumentValidator.AssertIsNotNull(() => property);
ArgumentValidator.AssertIsNotNull(() => columnName);
var propertyInfo = Reflect.Property<T>.InfoOf(property);
m_Map.Add(propertyInfo, columnName);
return this;
}
public Map Compile(){
return m_Map.TryGetValue;
}
所以用户会像这样使用它::
var map= new MapBuilder<MyClass>()
.Add(x => x.Name)
.Add(x => x.Id)
.Add(x => x.Active)
.Compile()
这将构建一个封装了 Name、Id、Active 这 3 个属性的映射。问题是 Map委托(delegate)现在可以将实现细节泄露给最终用户,因为他们可以观察到该方法是 TryGetValue Dictionary<PropertyInfo,string> 的方法目标将是私有(private)字典。您认为这是一种代码味道吗?
我可以将它包装在一个匿名方法中,但是当方法组转换成为可能时,我倾向于认为这种形式不好。
请您参考如下方法:
查看 Map 委托(delegate)的目标和方法所涉及的工作量与反射(reflect) MapBuilder 类本身的字段大致相同;无论哪种方式,调用者都可以发现私有(private) Dictionary 实例。
从 MapBuilder 类的角度来看,我不会担心它。反射(reflect)私有(private)字段肯定会产生代码味道:但这不是您的责任,而是您类(class)用户的责任。
