简体   繁体   中英

confuse with generic parameters in C#

I'm trying something like this

在此处输入图像描述

I use it here

客户

that is, I pass to Generic Method Print a list of Persons but inside the method, in data, I only have the standard methods of an object without any type.

How can I iterate the different kind of lists I will pass it?

Regards

When you have a generic method without any constraint you say: this method works for any type, be it an int , string or even any arbitrary type like MyType . This is usually not what you actually want.

Instead you seem to have a very specific requirement: not just any type, but only a few very specific ones . In order to describe those specific types you can add a generic constraint . In your case the data -parameter seems to allways be some collection, eg a list, so let´s update your signature a bit:

public int Print<T>(string concepto, List<T> data) { ... }

Now you still have the same problem. You still have no specifics on what the elements within the list look like. They can still be numbers, strings, dates or whatever. You can now use this in your Print :

public int Print<T>(string concepto, List<T> data)
{
    foreach(var element in data) ... // element is of type T which is object
}

Actually you know that only a few types are possible, eg only Person . Ideally those types implement a common interface which you could use for the generic constraint:

public int Print<T>(string concepto, List<T> data) { ... } where T: MyInterface

This assumes all your possible types implement MyInterface :

class Person : MyInterface { ... }

Now you can access every member that is defined for that interface within your print -method:

public int Print<T>(string concepto, List<T> data) where T: MyInterface
{
    foreach(var element in data)
    {
        var myMember = element.MyMember; // element is of type T which is MyInterface
    }
}

Modify your Print method to accept a generic type:

public int Print<T>(string concepto, IEnumerable<T> data)
{

}

Then, when you call it, pass the type, Person in this case:

 var result = repository.Print<Person>("subcontrationes", lista);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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