Limitations of generic methods and solutions to them

Source: Internet
Author: User
Tags reflection

The advantage of generics is that it improves the adaptability of the function and facilitates code reuse. However, in a method that supports generics, it is not known to represent the parameter type, and it is not possible to use its properties directly. Thus, this is a generic limitation that makes this generic parameter, and even the entire method, a convenience discount.

So, in a method that supports generics, a generic object is used as a parameter, and the main function is passed between different methods, like Buck. That's all.

Can't really access the properties of a generic object.

"You can use reflection," says Simon.

//propertyname, the property name to be accessed string getproperty<t> (ilist<t> listdb, string

            PropertyName) {String val = "";

            if (Listdb.count = = 0) return to Val; Gets the property array of the generic object by reflection propertyinfo[] Propertys = listdb[0]. GetType ().
            GetProperties ();
            int p = 0; foreach (PropertyInfo pi in propertys) {if pi. Name.equals (PropertyName, ComparisonType:StringComparison.CurrentCultureIgnoreCase)) {//Find PropertyName in T genus
                The subscript p break in the array of sex;
            } p++; } if (p = = Propertys.
            Length) {throw new Exception ("Object has no corresponding property:" + PropertyName); foreach (var m in listdb) {//So, the properties of the accessible t are val = propertys[p].g Etvalue (M).
                ToString () + ",";

            ...
            }
        return Val; }

Monkey Thunder.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.