Home > Backend Development > C++ > How Can I Retrieve a C# Class Reference from a String Using Reflection?

How Can I Retrieve a C# Class Reference from a String Using Reflection?

Linda Hamilton
Release: 2025-01-14 11:49:43
Original
545 people have browsed it

How Can I Retrieve a C# Class Reference from a String Using Reflection?

Use C# reflection to get class reference from string

In C#, obtaining a class reference from a string requires the use of reflection mechanism. Here’s how to do it:

Use the Type.GetType method:

  1. Type.GetType("FooClass"): Get the Type instance corresponding to the specified string (for example, "FooClass").
  2. Invoke(): To call a static method, such as FooClass.MyMethod(), you can use the Invoke() method to call on the retrieved MethodInfo object.

Example:

<code class="language-csharp">using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // 获取Type实例
        Type t = Type.GetType("FooClass");

        // 获取静态方法的MethodInfo
        MethodInfo method = t.GetMethod("MyMethod", BindingFlags.Static | BindingFlags.Public);

        // 调用方法
        method.Invoke(null, null);
    }
}

class FooClass
{
    public static void MyMethod()
    {
        Console.WriteLine("MyMethod invoked via reflection!");
    }
}</code>
Copy after login

This method retrieves the class reference directly from the string and calls the static method of the class.

The above is the detailed content of How Can I Retrieve a C# Class Reference from a String Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template