c# - Implementing collection of a generic class -


i trying create custom class follows.

public myclass<t>  {     public string value1 { get; set; }     public t value2 { get; set; }     public string value3 { get; set; } } 

the value of t either string or int or datetime .i assume can create new instance of class like

myclass<int> intclass = new myclass<int>(); myclass<string> stringclass=new myclass<string>(); 

and forth.

is possible create collection of above classes can put intclass , stringclass custom collection.

if want mix different generic types (so have collection containing both myclass<int> , myclass<string>) need define common base type or use collection not typed:

public class myclass<t> : myclass {     public t value2 { get; set; } }  public class myclass {     public string value1 { get; set; }     public string value3 { get; set; } } 

then can define collection like:

list<myclass> list = new list<myclass>(); list.add(new myclass<int>()); list.add(new myclass<string>()); 

you have cast results when retrieving entries in order access value2 property though.

another option avoid base-class use list<object>:

list<object> list = new list<object>(); list.add(new myclass<int>()); list.add(new myclass<string>()); 

but it's same problem above, plausibly worse (because can store anything in there)

edit: there various ways of how allow untyped access value2 in base non-generic myclass. 1 way define "untyped" version of on base class , override on subclass perform type-checking:

public abstract class myclass {     public string value1 { get; set; }     public abstract object value2untyped { get; set; }     public string value3 { get; set; } }  public class myclass<t> : myclass {     public t value2 { get; set; }      public override object value2untyped     {                 {             return value2;         }         set         {             value2 = (t)value;         }     } } 

then objects or collections typed against base non-generic myclass, can still access values, , set values @ runtime. (the set of course optional)


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -