c# - How to Invoke dynamicaly an anonymus objects function property? -


i extremely new in area every welcomed.

so have anonymous object(not sure thats correct name of it):

 var errors = new                 {                     error   = new func<bool>(() =>{ return true; })                     , error1  = new func<bool>(() => { return true; })                     , error2  = new func<bool>(() => { return true; })                     , error3  = new func<bool>(() => { return true; })                     , error4  = new func<bool>(() => { return true; })                     , error5  = new func<bool>(() => { return true; })                     , error6  = new func<bool>(() => { return true; })                     , error7  = new func<bool>(() => { return true; })                     , error8  = new func<bool>(() => { return true; })                     , error9  = new func<bool>(() => { return true; })                     , error10 = new func<bool>(() => { return true; })                     , error11 = new func<bool>(() => { return true; })                     , error12 = new func<bool>(() => { return true; })                 }; 

i want iterate through object properties , call them function.

i have made code far:

type type = errors.gettype(); methodinfo[] properties = type.getmethods();  foreach (methodinfo property in properties) {     delegate del = property.createdelegate(typeof(system.func<bool>));     console.writeline("name: " + property.name + ", value: " + del.method.invoke(errors,null));                                                                                 } 

this code found on internet, made adjustments throws exception:

"cannot bind target method because signature or security transparency not compatible of delegate type."

it doesn't means me.

as mentioned, great noob in c# appreciated.

you can't create methods in anonymous object. can have properties (that can delegates)...

so:

type type = errors.gettype();  // properties: propertyinfo[] properties = type.getproperties();  foreach (propertyinfo property in properties) {     // value of property, cast right type     func<bool> func = (func<bool>)property.getvalue(errors);      // call delegate (`func()` in case)     console.writeline("name: " + property.name + ", value: " + func()); } 

note without reflection, can call methods like:

bool res = errors.error1(); 

or

func<bool> func = errors.error1(); bool res = func(); 

note in general doing useless, because wrong pass anonymous object outside function defined it, , inside function know "shape" (you know properties has, , name)


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -