C# is a very powerful language. However for this "powerful" perspective, there are various way to achieve something and you might hover among which way to take (at least for me :D).
In this post I will focus on "Reflection" and introduce some small code spinets.
First we assume this trivial class is defined in Utility assembly.
In this post I will focus on "Reflection" and introduce some small code spinets.
First we assume this trivial class is defined in Utility assembly.
namespace Utility.Sample { public class Target { public string wrapByDoubleQuote(string text) { return "\"" + text + "\""; } } }
Get Type from String and Instantiate by Activator
// type from reflection Type type = Type.GetType("Utility.Sample.Target"); // instantiate object from Type Target target = Activator.CreateInstance(type) as Target; // invoke method normally Console.WriteLine(target.wrapByDoubleQuote("contents"));
Instantiate Object from ConstructorInfo and Invoke Method by Reflection
// type from reflection // or you can do typeof(Target); Type type = Type.GetType("Utility.Sample.Target"); // another way to instantiate object. Using ConstructorInfo!! ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); object target = constructor.Invoke(new object[] { }); // Get method object MethodInfo method = type.GetMethod("wrapByDoubleQuote"); // target type doesn't have to be Target class // invoke method reflectively Console.WriteLine(method.Invoke(target, new object[] {"contents"}));
Instantiate Object via ObjectHandle
// first argument is assembly name, 2nd argument is full class name ObjectHandle handle = Activator.CreateInstance("Utility", "Utility.Sample.Target"); Target target = handle.Unwrap() as Target; Console.WriteLine(target.wrapByDoubleQuote("contents"));
Instantiate Object From Assembly
// see defined method below Target target = CreateInstanceFromAssembly<Target>("Utility", "Utility.Sample.Target"); Console.WriteLine(target.wrapByDoubleQuote("contents"));
private static T CreateInstanceFromAssembly<T>(string assembly, string typeName) where T : class { var name = new AssemblyName(assembly); var asm = Assembly.Load(name); return asm.CreateInstance(typeName) as T; }
コメント