c# - Struct parameters in attributes -


i have got following sample code:

public struct testdata {     public readonly string element;     public readonly bool mandatoryind;      public testdata( string element, bool mandatoryind )     {         element = element;         mandatoryind = mandatoryind;     } }  [attributeusage( attributetargets.class, allowmultiple = false )] public class test : attribute {     public testdata[] values { get; set; }      public test( params testdata[] values )     {         this.values = values;     } } 

what want this:

[test( "3477", true, "3286", true, "3286", false )] public class testclass {  } 

basically, i'd pair of parameters (string, bool) captured in testdata() struct, not sure if it's possible this. have tried following, compile error "an attribute argument must constant expression, typeof expression or array creation expression of attribute parameter type".

[test( new testdata("3477", true), new testdata("3286", true), new testdata("3286", false) )] public class testclass {  } 

if isn't possible have consider using multiple attributes, doing @ moment want cleaner , more terser method.

this possible if change signature of constructor , use linq trick:

public test(params object[] values) {      this.values = values             .select((x, idx) => new {x, idx})             .groupby(g => g.idx/2)             .select(g => new testdata(g.first().x.tostring(), (bool) g.last().x))             .toarray();  } 

but indeed not type-safe.

note: may want use batch method morelinq code better.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -