c# - Method with generic return type but not generic input. Is this possible? -


suppose have nodedata class:

public class nodedata<t> {     public string name;     public t value;     public nodedata(string name, t value)     {         this.name = name;         this.value = value;     } } 

and base node class , child classes have several properties type nodadata:

public class node {     public list<nodedata<t>> listoutputs<t>()     {         var fieldinfos = gettype().getfields();         var list = new list<nodedata<t>>();         foreach (var item in fieldinfos)         {             type t = item.fieldtype;             string name = item.name;             if (t == typeof(nodedata<t>))             {                 var output = new nodedata<t>(name, default(t));                 list.add(output);             }         }         return list;     } }  public class testnode : node {     public nodedata<int> data;     public nodedata<double> data2;     public nodedata<double> data3;     public testnode ()     {         data = new nodedata<int>("test", 111);         data2 = new nodedata<double>("test", 113);     } } 

as can see there method lists outputs type t in node class can find output fields of child class in runtime:

testnode node = new testnode (); var list = node.listoutputs<int>(); // returns data 

but need know how use method list nodeoutputs of type t. in example int , double. need add method signature public list<nodedata<t>> listoutputs() // should return properties data, data2, data3. possible have method this? return type generic there no type argument method.

even after edit(s) not entirely clear trying achieve here assumptions: -you want have kind of node object acts container different types of nodedata elements. -you want able return 1 list node object contains nodedata elements stored in node container, regardless of nodedata objects' type.

instead of returning list> object listoutputs methods, return non-generic version of list object. don't have deal t in method call.

the logic loops through objects in non-generic list can examine type process contained nodedata objects correctly.

important note: proposed solution no means pretty think answers question. in opinion flawed oo point of view in presented code (e.g. use of reflection) , better solution have start changing underlying data structures. can done if have more information how used, e.g. kind of logic consumes returned list.


Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -