C# Type Class 타입 클래스

C# 2022. 7. 20. 00:12 |
반응형

Type 클래스를 사용해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Reflection;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Type t = typeof(String);
            //Type t = Type.GetType("System.String");
            String str = "";
            Type t = str.GetType();
            // Gets a Type object that represents the specified type.
 
            MethodInfo[] methods = t.GetMethods();
            foreach (MethodInfo method in methods)
            {
                // String 클래스의 Substring 함수는 2개의 오버로딩 함수가 있다.
                if (method.Name == "Substring")
                {
                    Console.WriteLine("- Method: " + method.Name);
 
                    ParameterInfo[] parameters = method.GetParameters();
                    foreach (ParameterInfo parameter in parameters)
                    {
                        Console.WriteLine("Parameter: " + parameter.Name);
                    }
                }
            }
 
            Console.WriteLine();
 
            MethodInfo substr = t.GetMethod("Substring"new Type[] { typeof(int), typeof(int) });
            // Searches for the specified method whose parameters match the specified generic
            // parameter count, argument types and modifiers, using the specified binding constraints.
 
            Object result = substr.Invoke("Hello, World!"new Object[] { 75 });
            // Invokes the method or constructor represented by the current instance, using the
            // specified parameters.
 
            Console.WriteLine("{0} returned \"{1}\".", substr, result);
        }
    }
}
 

 

소스를 빌드하고 실행한다.

 

 

반응형
Posted by J-sean
: