简体   繁体   中英

Accepting generic data type into a class constructor list

I wanted accept any type of the data in the list, please some one help. see the below method and class method which are in **.

public void SendEmail(string sender, EmailObjects emailObjects)

 public class EmailObjects 
    {
        public string EMAILLIST { get; set; }

        public string CC_EMAILLIST { get; set; }

        public string BCC_EMAILLIST { get; set; }

        public string subjectline { get; set; }

        **public List<T> lstOfValueToReplace { get; set; }**

        public string HTMLbody { get; set; }

        **public List<string>  lsthtmlBody { get; set; }**
    }

It actually depends on the context you are working in...

If the list can contain multiple types at once, you can use

List<object>

as anything in C# inherits from object class. But be carefull as you will have no idea of what the type is and you will have to perform checks for that.

If the list always contains the same data type, then you can use generics:

public class EmailObjects<TtoReplace, ThtmlBody>
{
    [...]

    public List<TtoReplace> lstOfValueToReplace { get; set; }**

    public string HTMLbody { get; set; }

    public List<ThtmlBody>  lsthtmlBody { get; set; }**
}

but that will imply the caller of this class to know which types will be contained in your list.

Martin Verjans' answers seems to be the simplest way but maybe you can use

public List<dynamic> DynamicList {get;set;}

You can check objects types this way:

 dynamic dynamicObject;

 dynamicObject = "I am a System.String";
 Console.WriteLine(dynamicObject.GetType()); //System.String

 dynamicObject = 420691337;
 Console.WriteLine(dynamicObject.GetType()); //System.Int32

 dynamicObject = new CustomClass
 {
    IntAttribute = 420691337,
    StringAttribute = "I am a System.String"
 };
 Console.WriteLine(dynamicObject.GetType()); //YourApplicationNamespace.CustomClass

dynamic type can be usefull especially if you are deserializing object retrieved from API calls for example because you can use expected attributes names to access the value.

var contacts = JsonConvert.DeserializeObject<dynamic>(contactsResponse.Content);
if (contacts.totalElements > 0) {
   // Do stuff
}

If you are targeting .NET Framework, you need to reference Microsoft.CSharp, it does not seem to be the case for .NET Core.

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