我创建了一个简单的类,它是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;
我收到以下错误消息:
“'对象'不包含”属性“的定义,也没有扩展方法”属性“接受第一个“对象”类型的参数可以找到“
我可以使用VB在即时窗口中解析该属性,但没有任何问题:
? _CurrentRow.PersonId
答案 0 :(得分:3)
看起来_CurrentRow
的类型为object
,但您希望在其上进行动态查找。如果是这种情况,则需要将类型更改为dynamic
dynamic _CurrentRow;
答案 1 :(得分:1)
您没有展示_CurrentRow
的声明。它应该声明为
dynamic _CurrentRow
以获得动态行为。