【问题标题】:Accessing DataContractJsonSerializer<T> properties via re-factored foreach loop通过重构的 foreach 循环访问 DataContractJsonSerializer<T> 属性
【发布时间】:2010-06-30 18:48:53
【问题描述】:

我有下面的代码。

string content = twitterMsg.text; 行正在为 twitterMsg 创建错误“使用未分配的局部变量”。我似乎无法访问我的 DataContractJsonSerializer&lt;TwitterMain&gt; 集合中的 TwitterSearchResponse.results.text 字段。

TwitterSearchResponse.results 是一个数组(一组对象属性),其中包含多个字符串字段,名称为textuser_info

有人可以帮忙吗?

更新代码如下。我仍然很困惑为什么我不能正确地迭代我的TwitterSearchResponse.results 并分配content = twitterMsg.text

对于它的价值,这是我的 DataContractJsonSerializer 方法:

String url = String.Format("http://search.twitter.com/search.json?q={0}&rpp=20", Server.UrlEncode(txtSearchFor.Text));


// parse the JSON data
using (MemoryStream ms = new MemoryStream(wc.DownloadData(url)))
{
    DataContractJsonSerializer jsonSerializer =
        new DataContractJsonSerializer(typeof(TwitterMain));
    TwitterSearchResponse = jsonSerializer.ReadObject(ms) as TwitterMain;  // read as JSON and map as TwitterOut
}

这是问题所在的原始发布代码。

    public List<MatchCollection> returnMatches(DataContractJsonSerializer<TwitterMain> TwitterSearchResponse)
{
        List<MatchCollection> messageLinks = new List<MatchCollection>();

        foreach (TwitterResult twitterMsg in TwitterSearchResponse.results)
        {
            string content = twitterMsg.text;

            // capture internet protocol pre-fixed words from message
            string pattern = @"...";
            messageLinks.Add(Regex.Matches(content, pattern, RegexOptions.IgnoreCase));

            // capture @username twitter users from message
            string atUsernamePattern = @"@([a-zA-Z0-9-_]+)";
            MatchCollection PeopleMatches = Regex.Matches(content, atUsernamePattern, RegexOptions.IgnoreCase);
        }

        return messageLinks;
}

【问题讨论】:

  • 我已经删除了我的 RegEx pattern,因为它使 SO 行为异常(不让我发帖!)

标签: c# asp.net .net datacontractjsonserializer


【解决方案1】:

我怀疑它实际上报告了使用未分配的局部变量MessageLinks。您对twitterMsg 的使用看起来不错。

所以,最大的问题是:如果没有任何结果,你想返回什么?如果您愿意返回 null,只需在声明 MessageLinks 时分配该值。

下一个问题:你真的只想返回你找到的最后一个MatchCollection吗?这就是当前的行为:您循环遍历所有变量,每次设置相同的局部变量(即替换前一个值),然后返回最后一个值。

最后一个问题:为什么你有骆驼大小写的方法名称 (returnMatches)、帕斯卡大小写的局部变量 (MessageLinks)、帕斯卡大小写的参数名称 (TwitterSearchResponse) 和骆驼式财产(text)?我会假设 text 是由于它以这种方式来自 JSON - 但最好遵循正常的 .NET 命名约定。

【讨论】:

  • 我似乎有自己的符号,几乎可以肯定它没那么有用。谢谢,我现在了解这个问题,并将确保我从现在开始保持良好的格式!
  • @Jon Skeet - 实际上我已经使用 public List&lt;MatchCollection&gt; returnMatches(DataContractJsonSerializer&lt;TwitterMain&gt; TwitterSearchResponse) 获取所有 MatchCollections,但 twitterMsg 仍然无法访问它的数据。
  • @AlexW:请发布实际代码 - 当然,如有必要,请省略该模式。您当前发布的代码不会导致您发布的错误消息。
  • 好的,现在很好,我运行了调试器,它以某种方式自行清除了。
猜你喜欢
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
相关资源
最近更新 更多