C# 원격 객체 생성

Featured image
- Activator는 클래스 메서드인 CreateInstance를 사용한다.


- Assembly는 인스턴스 메서드인 CreateInstance를 사용한다.


- FormatterServices는 클래스 메서드인 GetUnititializedObject를 사용한다.

assembly

// No parameter
// 1. Activator
var person_instance1 = Activator.CreateInstance(typeof(Person));
Console.WriteLine(person_instance1);
 
// 2. Assembly
var assem = Assembly.GetExecutingAssembly();
var typeName = assem.DefinedTypes.Where(val => val.Name == nameof(Person)).FirstOrDefault().FullName;
var person_instance2 = assem.CreateInstance(typeName, true);
Console.WriteLine(person_instance2);
 
// 3. FormaterServices 
var person_instance3 = FormatterServices.GetUninitializedObject(typeof(Person));
Console.WriteLine(person_instance3);
 
// Parameter
var parameter1 = new object[] { "홍길동", 30 };
var parameter2 = new object[] { "고길동", 35 };
 
var person_instance4 = Activator.CreateInstance(typeof(Person), BindingFlags.Public | BindingFlags.Instance, null, parameter1, CultureInfo.CurrentCulture, null);
Console.WriteLine(person_instance4);
 
var person_instance5 = assem.CreateInstance(typeName, true, BindingFlags.Public | BindingFlags.Instance, null, parameter2, CultureInfo.CurrentCulture, null);
Console.WriteLine(person_instance5);
 
// class
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
 
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
 
    public Person() : this("admin", 999)
    {
 
    }
 
    public override string ToString() => $"Name : {Name}, Age : {Age}";
}  

Reference

Activator 클래스 (System)

FormatterServices 클래스 (System.Runtime.Serialization)

Assembly.CreateInstance 메서드 (System.Reflection)