listitem如何投射或以其他方式

listitem如何投射或以其他方式

本文介绍了listitem如何投射或以其他方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误:无法将类型"System.Web.UI.WebControls.ListItem"转换为详细信息"


Error:Cannot convert type ''System.Web.UI.WebControls.ListItem'' to ''detail''


public class Detail
    {
        public int detailid;
        public string detailName;

       public override string ToString()
       {
           return detailName;
       }

       public Detail()
        {
            detailid = 0;
        }
}

 Detail detail=null;
 detail = (Detail)ChBoxList.Items[i];



我尝试过的事情:



What I have tried:

public class Detail : ListItem
    {
        public string detailid;
        public string detailName;
}




问题继续!




problems continue!

推荐答案

namespace WebApplication1
{

    public class Detail
    {
        public int detailid { get; set; }
        public string detailName { get; set; }

    }

    public static class DetailExtension
    {
        public static Detail ToDetail(this ListItem li)
        {
            Detail detail = new Detail();
            if (null != li)
            {
                detail.detailid = int.Parse(li.Value);
                detail.detailName = li.Text;
            }
            return detail;
        }
    }
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            List<Detail> lst = new List<Detail>();
            lst.Add(new Detail() { detailid = 1, detailName = "Detail 1" });
            lst.Add(new Detail() { detailid = 2, detailName = "Detail 2" });
            lst.Add(new Detail() { detailid = 3, detailName = "Detail 3" });

            ChBoxList.DataTextField = "detailName";
            ChBoxList.DataValueField = "detailid";
            ChBoxList.DataSource = lst;
            ChBoxList.DataBind();

            Detail item = ChBoxList.Items[1].ToDetail();

        }





    }


}


Detail detail = //...
int value;
if (int.Parse(ChBoxList.Items[i].Value, out value)) {
   DoSomethingWithDetail(detain, value);
   // ...
}


在此代码示例中,我没有使用您对类Detai的定义,因为它的定义不够好.使用public字段是不好的,属性通常用于非私有数据成员.为什么一切都是public为什么不是internal?您是否真的将那些成员暴露给其他程序集?另外,请避免使用太短的名称,例如i.名称应为有效的英语单词,变量的名词和一些非方法成员,方法成员应为动词.

—SA


In this code sample, I did not use your definition of the class Detai, because it is not good enough. Using public fields is bad, properties are usually used for non-private data members. And why everything is public why not internal? Do you really expose those members to other assemblies. Also, avoid too short names like i. Names should be valid English words, nouns for variables and some non-method members, and method members should be verbs.

—SA


这篇关于listitem如何投射或以其他方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:34