text
stringlengths
0
13.4k
public string Propertua {get; set;}
}
to set Propertua using reflection:
var typeOfClassy = typeof (Classy);
var classy = new Classy();
var prop = typeOfClassy.GetProperty("Propertua");
prop.SetValue(classy, "Value");
Section 10.4: How to create an object of T using Reflection
Using the default constructor
T variable = Activator.CreateInstance(typeof(T));
Using parameterized constructor
T variable = Activator.CreateInstance(typeof(T), arg1, arg2);
Section 10.5: Getting an attribute of an enum with reflection
(and caching it)
Attributes can be useful for denoting metadata on enums. Getting the value of this can be slow, so it is important to
cache results.
private static Dictionary<object, object> attributeCache = new Dictionary<object, object>();
public static T GetAttribute<T, V>(this V value)
where T : Attribute
where V : struct
{
object temp;
// Try to get the value from the static cache.
GoalKicker.com – .NET Framework Notes for Professionals
48
if (attributeCache.TryGetValue(value, out temp))
{
return (T) temp;
}
else
{
// Get the type of the struct passed in.
Type type = value.GetType();
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the custom attributes of the type desired found on the struct.
T[] attribs = (T[])fieldInfo.GetCustomAttributes(typeof(T), false);
// Return the first if there was a match.
var result = attribs.Length > 0 ? attribs[0] : null;
// Cache the result so future checks won't need reflection.
attributeCache.Add(value, result);
return result;
}
}
GoalKicker.com – .NET Framework Notes for Professionals
49
Chapter 11: Expression Trees
Section 11.1: building a predicate of form field == value
To build up an expression like _ => _.Field == "VALUE" at runtime.
Given a predicate _ => _.Field and a string value "VALUE", create an expression that tests whether or not the
predicate is true.
The expression is suitable for:
IQueryable<T>, IEnumerable<T> to test the predicate.
entity framework or Linq to SQL to create a Where clause that tests the predicate.
This method will build an appropriate Equal expression that tests whether or not Field equals "VALUE".
public static Expression<Func<T, bool>> BuildEqualPredicate<T>(
Expression<Func<T, string>> memberAccessor,
string term)
{
var toString = Expression.Convert(Expression.Constant(term), typeof(string));
Expression expression = Expression.Equal(memberAccessor.Body, toString);
var predicate = Expression.Lambda<Func<T, bool>>(
expression,
memberAccessor.Parameters);
return predicate;
}
The predicate can be used by including the predicate in a Where extension method.