简体   繁体   English

如何在 C# 中发送参数类并从中创建新对象

[英]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.这是和示例,我有 2 个类 Genre 和 Actors,这 2 个类有一个 sampe 属性名称。

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.在下面的代码中,我无法使用new T()创建新对象并填充属性。

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,另一种选择是发送一个 Func,

Change signature to:将签名更改为:

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

Instead of new T() , use createFunc(name) :而不是new T() ,使用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使用此方法时不需要new()约束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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