【问题标题】:"'object' does not contain a definition for 'property' and no extension method 'property' accepting a first argument of type 'object' could be found"“‘object’不包含‘property’的定义,并且找不到接受‘object’类型的第一个参数的扩展方法‘property’”
【发布时间】:2013-04-03 06:27:39
【问题描述】:

我创建了一个简单的类,它是 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' 的定义,并且没有扩展方法 'property' 接受第一个可以找到“对象”类型的参数”

我可以使用 VB 解决即时窗口中的属性,但没有任何问题:

? _CurrentRow.PersonId

【问题讨论】:

  • 也许只有我一个人......但我只是看不到你在哪里声明了 PersonId.. 它是一个属性吗?公共变量? .. 在哪儿?你如何声明_CurrentRow

标签: c# dynamicobject


【解决方案1】:

看起来_CurrentRow 被键入到object,但您希望对其进行动态查找。如果是这种情况,那么您需要将类型更改为dynamic

dynamic _CurrentRow;

【讨论】:

  • 是的,在我看来,您将其创建为“对象”类型。请注意,在 C# 中,多态性是显式的,因此即使您定义的是 DynamicCsv,如果给定类型是“object”,则只允许考虑“object”中的字段、方法和属性而无需强制转换。如前所述,您需要将其命名为动态,在调用 PersonId 之前将其转换为正确的类型,或者更好的是,为它使用静态类型。一般来说,如果您可以避免使用动态输入,请这样做,因为如果您不小心,它可能会导致输入问题。
  • 就是这样!一个小小的词就改变了一切,谢谢。
【解决方案2】:

您没有显示_CurrentRow 的声明。应该声明为

dynamic _CurrentRow 以获得动态行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多