Skip to content

Instantly share code, notes, and snippets.

@baba-s
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baba-s/9285116 to your computer and use it in GitHub Desktop.
Save baba-s/9285116 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Reflection;
/// <summary>
/// object型の拡張メソッドを管理するクラス
/// </summary>
public static class ObjectExtensions
{
private const string SEPARATOR = ","; // 区切り記号として使用する文字列
private const string FORMAT = "{0}:{1}"; // 複合書式指定文字列
/// <summary>
/// すべての公開フィールドの情報を文字列にして返します
/// </summary>
public static string ToStringFields<T>(this T obj)
{
return string.Join(SEPARATOR, obj
.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public)
.Select(c => string.Format(FORMAT, c.Name, c.GetValue(obj)))
.ToArray());
}
/// <summary>
/// すべての公開プロパティの情報を文字列にして返します
/// </summary>
public static string ToStringProperties<T>(this T obj)
{
return string.Join(SEPARATOR, obj
.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(c => c.CanRead)
.Select(c => string.Format(FORMAT, c.Name, c.GetValue(obj, null)))
.ToArray());
}
/// <summary>
/// すべての公開フィールドと公開プロパティの情報を文字列にして返します
/// </summary>
public static string ToStringReflection<T>(this T obj)
{
return string.Join(SEPARATOR, new [] { obj.ToStringFields(), obj.ToStringProperties() });
}
/// <summary>
/// 名前で指定されたメソッドを呼び出します
/// </summary>
public static object Invoke(this object obj, string methodName, params object[] parameters)
{
var method = obj.GetType().GetMethod(
methodName,
BindingFlags.Instance | BindingFlags.Public,
null,
Array.ConvertAll(parameters, c => c.GetType()),
null);
return method.Invoke(obj, parameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment