I have the following attribute and a property decorated with that attribute:
[AttributeUsage(AttributeTargets.Property)]
public class TestAttribute : Attribute
{
#region Properties
public string Test { get; private set; }
public string ResourceTest
{
get { return this.ResourceType.GetProperty(this.Test).GetValue(null) as string; }
}
public Type ResourceType { get; set; }
#endregion
#region Constructors
public TestAttribute(string test)
{
this.Test = test;
}
#endregion
}
public class Test
{
#region Properties
[Test("TestRes", ResourceType = typeof(Resources.Test)]
public string TestField { get; set; }
#endregion
}
Now i need to retrieve the ResourceTest
value from a Expression<Func<TModel, TValue>>
but the following code gives me a TargetException
at the return
line when i call GetResourceValue(o => o.TestField)
:
public static string GetResourceValue<TModel, TValue>(Expression<Func<TModel, TValue>> expression)
{
MemberExpression memberExpression = expression.Body as MemberExpression;
if (memberExpression != null && memberExpression.Member != null)
{
foreach (var attribute in memberExpression.Member.CustomAttributes)
{
switch (attribute.AttributeType.Name)
{
case "TestAttribute":
return (attribute.AttributeType.GetProperty("ResourceTest").GetValue(attribute) as string);
}
}
}
return null;
}
Is there another way to retrieve that property's value?
Aucun commentaire:
Enregistrer un commentaire