Skip to content

Instantly share code, notes, and snippets.

@miso-soup
Last active December 19, 2015 04:58
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 miso-soup/df08b5f1d309a6c94162 to your computer and use it in GitHub Desktop.
Save miso-soup/df08b5f1d309a6c94162 to your computer and use it in GitHub Desktop.
Hokuriku.NET C# メタプログラミング ~リフレクション~ http://atnd.org/events/40284 の時に書いたコード
using System;
using System.Reflection;
namespace アセンブリ
{
class Program
{
static void Main(string[] args)
{
Assembly asm = Assembly.LoadFrom(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Windows.Forms.dll");
dynamic form = asm.CreateInstance("System.Windows.Forms.Form");
dynamic button = asm.CreateInstance("System.Windows.Forms.Button");
button.Text = "Hello!!";
form.Text = "Hokuriku.NET C#";
form.Controls.Add(button);
form.ShowDialog();
Console.ReadKey();
}
}
}
using System;
using System.Reflection;
using System.Runtime.Remoting;
namespace インスタンス化
{
class Program
{
class Person
{
public Person()
{
}
public Person(String name)
{
this.Name = name;
}
public String Name { get; set; }
}
static void Main(string[] args)
{
{
Person person = Activator.CreateInstance<Person>();
person.Name = "Taro";
Console.WriteLine("1:{0}", person.Name);
}
{
ObjectHandle personObjectHandle = Activator.CreateInstance(null, "インスタンス化.Program+Person");
Person person = personObjectHandle.Unwrap() as Person;
person.Name = "Taro";
Console.WriteLine("2:{0}", person.Name);
}
{
ObjectHandle personObjectHandle = Activator.CreateInstanceFrom("インスタンス化.exe", "インスタンス化.Program+Person");
Person person = personObjectHandle.Unwrap() as Person;
person.Name = "Taro";
Console.WriteLine("3:{0}", person.Name);
}
{
ObjectHandle personObjectHandle = AppDomain.CurrentDomain.CreateInstance("インスタンス化", "インスタンス化.Program+Person");
Person person = personObjectHandle.Unwrap() as Person;
person.Name = "Taro";
Console.WriteLine("4:{0}", person.Name);
}
{
Type personType = typeof(Person);
ConstructorInfo constructorInfo = personType.GetConstructor(new Type[] { });
Person person = constructorInfo.Invoke(null) as Person;
person.Name = "Taro";
Console.WriteLine("5:{0}", person.Name);
}
//InvokeMember(BindingFlags.CreateInstance)
//配列とデリゲーとのインスタンスを作成する場合
//Array.CreateInstance(
//Delegate.CreateDelegate(
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace カスタム属性
{
class Program
{
//[AttributeUsage(AttributeTargets.Class)]
class SampleAttribute : Attribute
{
public SampleAttribute()
{
}
public SampleAttribute(String name)
{
}
}
/// <summary>
/// 哺乳類
/// </summary>
[Sample]
class Mammal
{
}
class Person : Mammal
{
}
//戻り値に属性付ける
[return:Sample]
[Conditional("DEBUG")]
static void Output()
{
Console.WriteLine("Output");
}
static void Main(string[] args)
{
Output();
Type personType = typeof(Person);
//カスタム属性がついているかどうかを取得する
{
Console.WriteLine("isDefined:{0} (inherit:false", personType.IsDefined(typeof(SampleAttribute), false));
Console.WriteLine("isDefined:{0} (inherit:true", personType.IsDefined(typeof(SampleAttribute), true));
}
//カスタム属性のインスタンスを取得する
{
object[] attributes = personType.GetCustomAttributes(inherit: true);
//object[] attributes = Attribute.GetCustomAttributes(personType);
foreach (object attribute in attributes)
{
Console.WriteLine(attribute);
}
}
//インスタンスを作らずに取得する
{
IList<CustomAttributeData> attributes =
CustomAttributeData.GetCustomAttributes(typeof(Mammal));
foreach (var attribute in attributes)
{
Console.WriteLine(attribute);
}
}
}
}
}
using System;
using System.Reflection;
namespace コンストラクタ
{
class Program
{
class Person
{
public Person()
{
}
public Person(String name)
{
this.Name = name;
}
static Person()
{
Console.WriteLine("static constructor 呼び出された");
}
public String Name { get; set; }
}
static void Main(string[] args)
{
Type personType = typeof(Person);
//引数なしのコンストラクタ
{
ConstructorInfo constructorInfo = personType.GetConstructor(new Type[] { });
Console.WriteLine("1:{0}", constructorInfo);
Person who = (Person)constructorInfo.Invoke(null);
Console.WriteLine("2:{0}", who.Name);
}
//String1つを引数にもつコンストラクタ
{
ConstructorInfo constructorInfo = personType.GetConstructor(new Type[] { typeof(String) });
Console.WriteLine("3:{0}", constructorInfo);
Person who = (Person)constructorInfo.Invoke(new object[] { "Taro" });
Console.WriteLine("4:{0}", who.Name);
}
//static constructor を呼ぶ方法
{
ConstructorInfo staticInfo = personType.GetConstructor(
BindingFlags.Static | BindingFlags.NonPublic,
null,
new Type[] { },
null);
Console.WriteLine("5:{0}", staticInfo);
//方法1
staticInfo.Invoke(null, null);
//方法2
personType.TypeInitializer.Invoke(null, null);
}
}
}
}
using System;
using System.Reflection;
namespace フィールド
{
class Program
{
class Person
{
public double Height;
public string Name { get; set; }
}
static void Main(string[] args)
{
Type personType = typeof(Person);
Person kaba = new Person();
{
FieldInfo fieldInfo = personType.GetField("Height");
Console.WriteLine("1:{0}",fieldInfo);
}
//プライベートなフィールドを取得し、値を設定する
FieldInfo[] fields = personType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance );
foreach (FieldInfo fieldInfo in fields)
{
fieldInfo.SetValue(kaba, "kabakiyo");
Console.WriteLine("2:{0}", kaba.Name);
Console.WriteLine("3:{0}", fieldInfo);
}
}
}
}
using System;
using System.Reflection;
namespace プロパティ
{
class Program
{
class Person
{
public string Name { get; set; }
private double Weight { get; set; }
}
static void Main(string[] args)
{
Type personType = typeof(Person);
//プロパティ情報をとる
PropertyInfo[] properties =
personType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property);
}
/*
* MSDN
* BindingFlags 列挙体
* Type.GetProperties メソッド
*/
Person kaba = new Person();
kaba.Name = "Kabakiyo";
PropertyInfo kabaPropertyNameInfo = personType.GetProperty("Name");
//プロパティに値をセット
{
kabaPropertyNameInfo.SetValue(kaba, "Kabakiyo2");
Console.WriteLine(kaba.Name);
}
//プロパティの値を取得
{
String name = (string)kabaPropertyNameInfo.GetValue(kaba);
Console.WriteLine(name);
}
//--private な変数にもアクセスできる
foreach (MethodInfo accessor in kabaPropertyNameInfo.GetAccessors())
{
Console.WriteLine(accessor);
}
}
}
}
using System;
using System.Reflection;
namespace メソッド
{
class Program
{
class Person
{
public void Run()
{
Console.WriteLine("I Run");
}
public void Run(string name)
{
Console.WriteLine("{0} Run", name);
}
public static void Live()
{
Console.WriteLine("Live!");
}
}
static void Main(string[] args)
{
Type personType = typeof(Person);
Person person = new Person();
{
MethodInfo info = personType.GetMethod("Run", new Type[] { });
Console.WriteLine(info); //Void Run()
}
{
MethodInfo info = personType.GetMethod("Run", new Type[] { typeof(string) });
Console.WriteLine(info); //Void Run(System.String)
}
//static
{
MethodInfo info = personType.GetMethod("Live");
Console.WriteLine(info);
}
//メソッドを呼び出す
{
MethodInfo info = personType.GetMethod("Live");
info.Invoke(person, null);
}
{
MethodInfo info = personType.GetMethod("Run", new Type[] { typeof(string) });
info.Invoke(person, new object[] { "taro" });
}
}
}
}
using System;
using System.Reflection;
namespace メンバー
{
class Program
{
class Person
{
public Person()
{
}
public String Name { get; set; }
public void Run()
{
}
public void RunPartial()
{
}
}
static void Main(string[] args)
{
//MemberInfo
//Type, PropertyInfo, FieldInfo, MethodInfo,
//ConstructorInfo, EventInfo 基底クラス
Type personType = typeof(Person);
{
Console.WriteLine("★Members");
MemberInfo[] members = personType.GetMembers();
foreach (MemberInfo member in members)
{
Console.WriteLine("Member:{0}", member);
Console.WriteLine("DeclaringType:{0}", member.DeclaringType);
Console.WriteLine("MemberType:{0}", member.MemberType);
Console.WriteLine("Module:{0}", member.Module);
Console.WriteLine("Name:{0}", member.Name);
Console.WriteLine("ReflectedType:{0}", member.ReflectedType);
Console.WriteLine();
}
}
{
MemberInfo[] runMembers = personType.GetMember("Run");
Console.WriteLine("★RunMembers");
foreach (MemberInfo member in runMembers)
{
Console.WriteLine("member:{0}", member);
}
}
{
MemberInfo[] runMembers = personType.GetMember("Ru*");
Console.WriteLine("★Ru*");
foreach (MemberInfo member in runMembers)
{
Console.WriteLine(member);
}
}
/*
* .ToString()
* DeclaringType は object
* ReflectedType は Person
*/
Person kaba = new Person();
//Name に InvokeMember を使って値をセットする
personType.InvokeMember(
name: "Name",
invokeAttr: BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
binder: null,
target: kaba,
args: new object[] { "kabakiyo" });
//peronType.GetProperty("Name").SetValue(kaba, "kabakiyo");
Console.WriteLine("kaba.name : {0}", kaba.Name);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace 問題
{
class Program
{
static void Main(string[] args)
{
var personValues = new Dictionary<Expression<Func<Person, object>>, object>();
personValues[m => m.Name] = "kabakiyo";
personValues[m => m.Age] = 13;
//問題:上の情報を使って、Personのプロパティに値を設定せよ
var person = new Person(personValues);
Console.WriteLine("Name:{0}", person.Name);
Console.WriteLine("Age:{0}", person.Age);
}
class Person
{
public Person(Dictionary<Expression<Func<Person, object>>, object> propertyValueInfos)
{
//プロパティに値を設定する
foreach (var propertyValueInfo in propertyValueInfos)
{
String propertyName = String.Empty;
if (propertyValueInfo.Key.Body is UnaryExpression)
{
var memberEx = ((MemberExpression)((UnaryExpression)propertyValueInfo.Key.Body).Operand);
propertyName = memberEx.Member.Name;
}
else
{
propertyName = ((MemberExpression)propertyValueInfo.Key.Body).Member.Name;
}
PropertyInfo propertyInfo = this.GetType().GetProperty(propertyName);
propertyInfo.SetValue(this, propertyValueInfo.Value);
}
}
public String Name { get; set; }
public int Age { get; set; }
}
}
}
using System;
using System.Collections.Generic;
namespace 型
{
class Program
{
class Person
{
}
static void Main(string[] args)
{
//静的に型の情報をとる
{
Type type = typeof(Person);
Console.WriteLine("1:{0}", type); //型.Program+Person // + : InnerClass
}
//インスタンスから型の情報をとる
{
var person = new Person();
Type type = person.GetType();
Console.WriteLine("2:{0}", type); //型.Program+Person
}
//TypeName から型の情報をとる
{
Type type = Type.GetType("型.Program+Person"); //フルネームじゃないと取れない
Console.WriteLine("3:{0}", type);
}
//ジェネリックの型を取る
{
Type type = typeof(Dictionary<,>);
Console.WriteLine("4:{0}", type);//System.Collections.Generic.Dictionary`2[TKey, TValue]
}
//型情報をつくる Dictionary<string, int>
{
Type type = typeof(Dictionary<,>);
Type type2 = type.MakeGenericType(
new Type[] { typeof(string), typeof(int) });
Console.WriteLine("5:{0}", type2); //System.Collections.Generic.Dictionary`2[string, int]
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment