|
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace MultiSortDemo
{
/// <summary>
/// Used on Properties
/// This attribute specifies which underlying field name the property is associated with.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class PropertyFieldName : System.Attribute
{
protected string sFieldName;
public PropertyFieldName(string fieldName) { sFieldName = fieldName; }
public string FieldName { get { return sFieldName; } }
}
public class PropertyFieldMappings<T> where T : class
{
/// <summary>
/// Set up a hashtable for quick lookup of field names associated with a property name
/// </summary>
private static Dictionary<string, string> htPropertyFieldMapping = new Dictionary<string, string>(16);
public string GetFieldNameForProperty(string sPropertyName)
{
string sFieldName;
// Check the hashtable/dictionary to see if we have already mapped this field-property association
if (htPropertyFieldMapping.TryGetValue(sPropertyName, out sFieldName))
{
return sFieldName;
}
PropertyInfo propInfo = typeof(T).GetProperty(sPropertyName);
if (propInfo == null)
{
throw new Exception("Property name " + sPropertyName + " not found on class type " + typeof(T).Name);
}
object[] rgCustomAttributes = propInfo.GetCustomAttributes(typeof(PropertyFieldName), true);
if (rgCustomAttributes == null || rgCustomAttributes.Length == 0)
{
throw new Exception("Property " + sPropertyName + " is not marked with the PropertyFieldName attribute");
}
PropertyFieldName propFieldName = (PropertyFieldName)rgCustomAttributes[0];
sFieldName = propFieldName.FieldName;
// Now that we have the field name, confirm it exists
FieldInfo fieldInfo = typeof(T).GetField(
sFieldName, BindingFlags.FlattenHierarchy | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
// All is okay, add the mapping to the hashtable/dictionary
htPropertyFieldMapping.Add(sPropertyName, sFieldName);
return sFieldName;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Currently working as a Senior Silverlight Developer with Troppus Software in Superior, CO. I enjoy statistics, programming, new technology, playing the cello, and reading codeproject articles.