Getting a C# .NET Resource Property Name By Explicitly Referencing The Property
Got a bit of an odd one but there's a reason behind my madness.
I have a resource I have set up with some string properties on it, for example MenuAdminLabel
and MenuAccountsLabel
that have values like "Admin" and "Accounts" respectively. I need to pass the label property names into a method and I'm well aware I could just pass these in as strings like "MenuAdminLabel" and "MenuAccountsLabel" but I would like these to be validated by the compiler rather than being simple strings as there will be a lot of properties on the resource and I want to ensure each reference is correct.
The trouble is if I access Resource.MenuAdminLabel
I (obviously) get the value of the resource property rather than the property name, I can access the property list by using typeof(Localisation.Resources).GetProperties()
but, again, I'm having to use a literal string to get the property name from this rather than something explicitly using Localisation.Resource.MenuAdminLabel
that the compiler can validate.
How can I do this?
That's a problem often faced when implementing INotifyPropertyChanged. The solution is to use a lambda expression like
MyMethod(() => Localisation.MenuAdminLabel);
instead of
MyMethod("MenuAdminLabel");
and analyse the expression. One example implementation can be found in this answer. For your case, it might look like:
private void MyMethod<TValue>(Expression<Func<TValue>> propertySelector)
{
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException();
string name = memberExpression.Member.Name;
// Do stuff with name
}
精彩评论