Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can't really do this, unless you're using C# 3.0 in which case you'll need to rely on LINQ (ehm, expression trees).</p> <p>What you do is that you create a dummy method for a lambda expression which lets the compiler generate the expression tree (compiler does the type checking). Then you dig into that tree to get the member. Like so:</p> <pre><code>static FieldInfo GetField&lt;TType, TMemberType&gt;( Expression&lt;Func&lt;TType, TMemberType&gt;&gt; accessor) { var member = accessor.Body as MemberExpression; if (member != null) { return member.Member as FieldInfo; } return null; // or throw exception... } </code></pre> <p>Given the following class:</p> <pre><code>class MyClass { public int a; } </code></pre> <p>You can get the meta data like this:</p> <pre><code>// get FieldInfo of member 'a' in class 'MyClass' var f = GetField((MyClass c) =&gt; c.a); </code></pre> <p>With a reference to that field you can then dig up any attribute the usual way. i.e. reflection.</p> <pre><code>static TAttribute GetAttribute&lt;TAttribute&gt;( this MemberInfo member ) where TAttribute: Attribute { return member.GetCustomAttributes( typeof( TAttribute ), false ) .Cast&lt;TAttribute&gt;().FirstOrDefault&lt;TAttribute&gt;(); } </code></pre> <p>Now you can dig up an attribute on any field by something which is in large checked by the compiler. It also works with refactoring, if you rename 'a' Visual Studio will catch that.</p> <pre><code>var attr = GetField((MyClass c) =&gt; c.a).GetAttribute&lt;DisplayNameAttribute&gt;(); Console.WriteLine(attr.DisplayName); </code></pre> <p>There's not a single literal string in that code there.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload