开发者

Why cant I create a generic list of my class type?

public partial class About : System.Web.UI.Page
{
    public class Class2
    {
        public int i = 1;
        public string str = "Chandan";

    }


    protected void Page_Load(object sender, Ev开发者_StackOverflow社区entArgs e)
    {

        List<Class2> Object2 = new List<Class2>();

    }

}


You are creating a collection of your objects.

In order to access the public fields of each object, you need to access each object in the list.

Did you mean?

Class2 Object2 = new Class2();


List<Class2> Object2 = new List<Class2>();
Object2.Add(new Class2());
Console.WriteLine(Object2[0].str);

I see no reason why Object2[0] shouldn't have accessible fields. And I just tested in LinqPad, and it worked correctly.

Or alternatively without a List:

Class2 Object2 = new Class2();
Console.WriteLine(Object2.str);

It's usually bad style to use public fields, but apart from that your code is ok and works.


List<Class2> Object2 = new List<Class2>(new[]{ new Class2(); });
Console.Out("{0}. {1}", Object2[0].i, Object2[0].str);

Should work fine.


Output of the following code List count = 1

public partial class About : System.Web.UI.Page
{
    public class Class2
    {
        public int i = 1;
        public string str = "Chandan";
        public string Data()
        {
            return i.ToString() + " " + str.ToString();
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {

        Class2 Object1 = new Class2();
        List<Class2> Object2 = new List<Class2>();
        Object2.Add(Object1);
        Response.Write("List count = " + Object2.Count.ToString());    
    }

}

You are right Matt. Thanks for the explanation. You Rock!!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜