using System;
using System.Reflection;
namespace Xylem.Common.Utils.ClassAccess
{
///
/// Access to private methods of any class by System.Reflection
///
public static class ClassAccess
{
///
/// Access private or public methods by name
///
///
///
/// class reference
/// method in class
/// optional parameters
///
///
///
/// - Initial.
///
public static TReturn CallMethode(TInstance classInstance, String methodName,
Object[] parameters = null, Boolean isPrivateMethod = false)
{
var type = classInstance.GetType();
BindingFlags bindingFlags;
if (isPrivateMethod)
{
bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
}
else
{
bindingFlags = BindingFlags.Public | BindingFlags.Instance;
}
var method = type.GetMethod(methodName, bindingFlags);
if (method != null)
{
return (TReturn)method.Invoke(classInstance, parameters);
}
return default(TReturn);
}
///
/// Getting the value of a property referenced by the name
///
///
///
///
///
///
/// false if property cannot be found or accessed
///
/// - Initial.
///
public static Boolean GetPropertyValue(TObj obj, String propertyName, out TType value)
{
value = default(TType);
if (obj == null)
return false;
var property = typeof(TObj).GetProperty(propertyName);
if (property is null)
return false;
value = (TType)property.GetValue(obj, null);
return true;
}
///
/// Setting the value of a property referenced by the name
///
///
///
///
///
///
/// false if property cannot be found or accessed
///
/// - Initial.
///
public static Boolean SetPropertyValue(TObj obj, String propertyName, TType value)
{
if (value == null || obj == null)
return false;
var property = typeof(TObj).GetProperty(propertyName);
if (property is null || !property.CanWrite)
return false;
property.SetValue(obj, value);
return true;
}
///
/// Copy all properties.
///
///
///
///
/// false if property cannot be found or accessed
///
/// - Initial.
///
public static Boolean CopyAllProperties(TObj destination, TObj source)
{
var type = typeof(TObj);
foreach (var prop in type.GetProperties())
{
if (prop.CanWrite)
prop.SetValue(destination, prop.GetValue(source, null), null);
}
return true;
}
}
}