我创建了一个简单的类,它是 DynamicObject 的后代:
public class DynamicCsv : DynamicObject
{
private Dictionary<string, int> _fieldIndex;
private string[] _RowValues;
internal DynamicCsv(string[] values, Dictionary<string, int> fieldIndex)
{
_RowValues = values;
_fieldIndex = fieldIndex;
}
internal DynamicCsv(string currentRow, Dictionary<string, int> fieldIndex)
{
_RowValues = currentRow.Split(',');
_fieldIndex = fieldIndex;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
dynamic fieldName = binder.Name.ToUpperInvariant();
if (_fieldIndex.ContainsKey(fieldName))
{
result = _RowValues[_fieldIndex[fieldName]];
return true;
}
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dynamic fieldName = binder.Name.ToUpperInvariant();
if (_fieldIndex.ContainsKey(fieldName))
{
_RowValues[_fieldIndex[fieldName]] = value.ToString();
return true;
}
return false;
}
}
我通过执行以下操作来使用后代对象:
protected string[] _currentLine;
protected Dictionary<string, int> _fieldNames;
...
_fieldNames = new Dictionary<string, int>();
...
_CurrentRow = new DynamicCsv(_currentLine, _fieldNames);
当我尝试使用带有点符号的 _CurrentRow 时:
int x = _CurrentRow.PersonId;
我收到以下错误消息:
“‘ object ’不包含‘ property ’的定义,并且找不到接受‘object’类型的第一个参数的扩展方法‘ property ’”
我可以使用 VB 解决即时窗口中的属性,但没有任何问题:
? _CurrentRow.PersonId