简体   繁体   中英

How to send parameter class and create new object from it in C#

Is that posible to send parameter class and create new object from it in method ?

So i want to create a method will return List of object in Generic.

This is and example, i have 2 class Genre and Actors and this 2 classes have a sampe properties Name.

Genre Class

public class Genre
{
    public string Name {get;set;}
}

Actor Class

 public class Actor
 {
     public string Name {get;set;}
 }

Program Class

public class Program
{
    public static void Main()
    {
        string test = "Adam,John,dan";
        string test2 = "Comedy,Action";
        List<Genre> a=  ConvertStringToList<Genre>(test2);
        List<Actor> b=  ConvertStringToList<Actor>(test);
    }

    public static List<T> ConvertStringToList<T>(string genreList) where T :new()
    {
        List<T> genres = new List<T>();
        foreach(var str in genreList.Split(','))
        {
            string Name = str.Trim();
            genres.Add(new T(){Name});

        }
        return genres;
    }
}

in code below i cant create new object using new T() and fill the properties.

any idea for solve this problem ?

One option is to create an interface and use that as constraint

Create an interface and implement:

public interface IName
{
    string Name {get;set;}
}


public class Genre: IName
{
    public string Name {get;set;}
}

public class Actor: IName
{
    public string Name {get;set;}
}

And use:

where T : IName, new()

Now you could do:

var t = new T();
t.Name = name;

Func

Another option is to send a Func,

Change signature to:

ConvertStringToList<T>(string genreList, Func<string, T> createFunc)

Instead of new T() , use createFunc(name) :

string name = str.Trim();
genres.Add(createFunc(name));

Usage:

ConvertStringToList<Genre>(test2, name => new Genre{Name = name});

PS. No need for the new() constraint when using this method

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