C#泛型的问题 [英] C# generics question

查看:143
本文介绍了C#泛型的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图完成从一本书上泛型的实践问题,但这个问题没有意义了我。在这里,它去。

I'm trying to complete a practice question from a book on generics but the question doesn't make sense to me. Here it goes.

创建两个类具有相同的功能。使用泛型的头等舱,投第二类对象类型。对于使用类和对象的基础类,以确定哪个性能更好循环创建。

Create two classes with identical functionality. Use generics for the first class, and cast the second class to Object types. Create a for loop that uses class and the Object based class to determine which performs better.

我不知道这意味着什么强制转换为对象类型。这里是我到目前为止的代码

I'm not sure what it means by casting to Object types. Here is my code so far

   //Generic
    class Person<T> {

        T var1;

        public Person(T yer) {
            var1 = yer;
        }

        public T Value { get { return var1; } }
    }

    //Normal class
    class Human {

        int var1;

        public Human(int yer) {
            var1 = yer;
        }

        public int Value { get { return var1; } }
    }



我的运行循环主程序

My main program running the loops

for (int i = 0; i < 1000000; i++) {
                Person<int> me = new Person<int>(1);
                int hey = me.Value;
            }

            for (int i = 0; i < 1000000; i++) {
                Human per = new Human(1);
                object her = (object)per.Value;
            }



我不知道林这样做的权利。请帮助: - )

I don't know if Im doing this right. Help please :-)

推荐答案

我觉得这个问题是问你创建一个集合类,并插入你的类实例。成

I think that the question is asking you to create a collection class, and insert instances of your class into that.

例如,

泛型版本:

List<Human> myList = new List<Human>();
Human h = new Human();
myList.Add(h);

对象的版本:

ArrayList myObjectList = new ArrayList();
Human h = new Human();
myObjectList.Add((object)h));



我没有检查是否是编译,并立即运行。

I haven't checked whether that compiles, and have to run now.

这篇关于C#泛型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆