-
-
Save takeshik/2757138 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Reflection; | |
namespace TrimStringTest | |
{ | |
/// <summary> | |
/// テストデータ | |
/// </summary> | |
struct A | |
{ | |
String a; | |
public A(String a) | |
{ | |
this.a = a; | |
} | |
}; | |
/// <summary> | |
/// テストデータ | |
/// </summary> | |
class B | |
{ | |
int b = 123; | |
string c = " c "; | |
String d = " d"; | |
}; | |
/// <summary> | |
/// テストデータ | |
/// </summary> | |
class C | |
{ | |
A e = new A(" e"); | |
B[] f = new B[3] { new B(), new B(), new B() }; | |
B g = new B(); | |
string h = " h"; | |
int i = 123; | |
}; | |
public static class EnumeraleEx | |
{ | |
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) | |
{ | |
foreach (var e in source) | |
{ | |
action(e); | |
} | |
} | |
} | |
class Program | |
{ | |
public static IEnumerable<Object> EnumTargetTypes(object obj) | |
{ | |
return obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) | |
.SelectMany(f => f.FieldType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(f.FieldType) | |
? ((IEnumerable) f.GetValue(obj)).Cast<object>().SelectMany(EnumTargetTypes) | |
: new[] { f.GetValue(obj), } | |
); | |
} | |
public static IEnumerable<T> EnumTargetTypes<T>(object obj) | |
{ | |
return EnumTargetTypes(obj).OfType<T>(); | |
} | |
public static void ActionTargetType<T>(object obj, Func<T, T> action) | |
{ | |
obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) | |
.ForEach(f => | |
{ | |
if (f.FieldType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(f.FieldType)) | |
{ | |
((IEnumerable) f.GetValue(obj)).Cast<object>().ForEach(e => ActionTargetType<T>(e, action)); | |
} | |
else if (typeof(T).IsAssignableFrom(f.FieldType)) | |
{ | |
var v = f.GetValue(obj); | |
f.SetValue(obj, action((T) v)); | |
} | |
}); | |
} | |
/// <summary> | |
/// Main() | |
/// </summary> | |
/// <param name="args"></param> | |
static void Main(string[] args) | |
{ | |
C c = new C(); | |
foreach (String str in EnumTargetTypes<String>(c)) | |
{ | |
Console.WriteLine("{0}", str); | |
} | |
ActionTargetType<String>(c, (string member) => member = member.Trim()); | |
foreach (String str in EnumTargetTypes<String>(c)) | |
{ | |
Console.WriteLine("{0}", str); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment