我一直在使用自定义动态对象来访问基础数据行或字典,例如:
public class DictionaryX : DynamicObject
{
private readonly Dictionary<string, string> _dict;
public DictionaryX(Dictionary<string, string> dict) { _dict = dict; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var retVal = _dict.ContainsKey(binder.Name);
result = retVal ? _dict[binder.Name] : null;
return retVal;
}
}
这使得读取和编写代码变得更加容易,例如在DataRow的情况下
var fullName = row.Name + row.Surname;
而不是
var fullName = row.Field("Name") + row("Surname");
但我们真正想要的是被访问的属性是字符串而不是动态。数据始终是底层对象中的字符串,但在某些地方我们必须将其转换为字符串或将它们声明为字符串而不是&#39; var&#39;否则我们可能会遇到编译或运行时错误,例如传递给其他方法时
string fullName = row.Name + row.Surname
DoSomething(fullName);
DoSomethingElse((string)row.Surname);
这解决了使其更好的代码使用的一些工作。我想创建一个允许我以这种方式编写代码的DynamicStringObject,但是访问的属性总是字符串,但我不确定从哪里开始。