Pass a C# property name as a parameter to an utility class method
is possible pass property of class method (outside of class) , retrieve property's description?
for example:
public class foo { [description("tells whether true or not.")] public bool someflag; public dosomethingneat() { myutility.getdescription(someflag); } }
and pseudo-code in utility class:
public static class myutility { public static string getdescription(??? property) { return property.description; } }suppose might necessary additionally pass type property belongs to.
gaea. i cooked same thing earlier. might post confirmation idea of using expression reasonable way of identifying member access @ compile time (as opposed string.)
the function "getdescription" gets description of member accessing in given lambda expression.
using system; using system.componentmodel; using system.linq.expressions; public class foo { [description( "the first property." )] public int property1; [description( "the second property." )] public string property2; } class program { static string getdescription<t>( expression<func<t>> expr ) { var mexpr = expr.body memberexpression; if( mexpr == null ) return null; if( mexpr.member == null ) return null; object[] attrs = mexpr.member.getcustomattributes( typeof( descriptionattribute ), false ); if( attrs == null || attrs.length == 0 ) return null; descriptionattribute desc = attrs[0] descriptionattribute; if( desc == null ) return null; return desc.description; } static void main( string[] args ) { foo foo = new foo(); console.writeline( getdescription( () => foo.property1 ) ); console.writeline( getdescription( () => foo.property2 ) ); } }
Visual Studio Languages , .NET Framework > Visual C#
Comments
Post a Comment