Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Thanks everyone who has taken the time to answer and discuss my question. </p> <p>Just to let you know, I have implemented a solution that is sufficient for my needs. The solution is not general, and it has some pitfalls, but I'd thought I share it anyway in case it can be of help to someone else.</p> <p>This is in principle what the class that is used when defining fields looks like:</p> <pre><code>public class Unit : IUnit { public NameOfField { get; set; } ... } </code></pre> <p>As you can see, the class implements the IUnit interface, and I have provided a public setter in the NameOfField property.</p> <p>The static fields are typically defined like this within some containing class:</p> <pre><code>public static Unit Hectare = new Unit(); </code></pre> <p>My solution is to set the NameOfField property through reflection before the field is used in the implementation. I do this through a static constructor (that of course needs to be invoked before the Unit fields are accessed. I use Linq to traverse the executing assembly for the relevant fields, and when I have detected these fields (fields which type implements the IUnit interface), I set the NameOfField property for each of them using the Any extension method:</p> <pre><code>Assembly.GetExecutingAssembly().GetTypes(). SelectMany(type =&gt; type.GetFields(BindingFlags.Public | BindingFlags.Static)). Where(fieldInfo =&gt; fieldInfo.FieldType.GetInterfaces().Contains(typeof(IUnit))). Any(fieldInfo =&gt; { ((IUnit)fieldInfo.GetValue(null)).NameOfField= fieldInfo.Name; return false; }); </code></pre> <p>There are some shortcomings with this approach:</p> <ul> <li>The static constructor has to be invoked through manual intervention before any Unit fields can be accessed</li> <li>The NameOfField setter is public. In my case this is no problem, but it might be when applied in other scenarios. (I assume that the setter could be made private and invoked through further reflection, but I have not taken the time to explore that path further.)</li> <li>... ?</li> </ul> <p>Either way, maybe this solution can be of help to someone else than me.</p>
    singulars
    1. This table or related slice is empty.
    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. 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