简体   繁体   English

我如何从asp.net(aspx)页面枚举静态类中包含的静态字典

[英]How do I enumerate a static dictionary contained in a static class from asp.net ( aspx) page

I don't understand how to loop over a static dictionary contained in a static class from my aspx page. 我不明白如何在我的aspx页面上遍历包含在静态类中的静态字典。 I have this for the static class 我有这个静态课程

public static class ErrorCode  

{
    public static IDictionary<int, string> ErrorCodeDic;

    static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<int, string>()
        { 
            {1, "a problem"},
            {2, "b problem"}
        };
    }
}

MORE SPECIFIC I can get it to work by spelling it out like this in the aspx part 更具体的说,我可以通过在aspx部分中将其拼写出来来使其工作

foreach( System.Collections.generic.KeyValuePair<int, string> kvp in MyLibrary.Dictionaries.ErrorCode.ErrorCodeDic) 

But I thought I could shorthand it by declaring variables in the code behind? 但是我想我可以通过在后面的代码中声明变量来简化它?

Public KeyValuePair<int, string> error;
Public ErrorCode.ErrorCodeDic ErrorCodes; OR
Public ErrorCode.ErrorCodeDic ErrorCodes = ErrorCode.ErrorCodeDic; "

I get build errors "The type name 'ErrorCodeDic' does not exist in the type ErrorCode. 我收到构建错误“类型名称'ErrorCodeDic'在类型ErrorCode中不存在。

And then in the aspx page use 然后在aspx页面中使用

foreach( error in ErrorCodes)

You can loop over all pairs like this: 您可以像这样遍历所有对:

foreach( KeyValuePair<int, string> kvp in ErrorCode.ErrorCodeDic)
{
  Response.Write(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}

For your updated case, in the code-behind: 对于您更新的案例,在后面的代码中:

public IDictionary<int, string> ErrorCodes = MyLibrary.Dictionaries.ErrorCode.ErrorCodeDic;

in the aspx: 在aspx中:

foreach(var error in ErrorCodes) { }

Alternatively, nothing in the codebehind, and this in the aspx: 另外,在代码背后也没有任何内容,而在aspx中有:

<%@ Import Namespace="MyLibrary.Dictionaries" %>
....Content...
<% foreach(var error in ErrorCode.ErrorCodeDic) { %>
  .. something ..
<% } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM