C# .net8 ~ 傳入字串 轉換成 物件成員名稱並取回對應數值

C# .net8 ~ 傳入字串 轉換成 物件成員名稱並取回對應數值

C# .net8 ~ 傳入字串 轉換成 物件成員名稱並取回對應數值


資料來源: chatgpt


C#線上編譯: https://dotnetfiddle.net/


問題:

C# .net8 假設有一CLASS 如下
public class A
{
int a;
int b;
}
有辦法設計一個函數 傳入字串 轉換成 物件成員名稱 取並回對應範例


Code:

using System;
using System.Reflection;
/*
是的,在 .NET 8 / C# 中,你可以使用 Reflection 或 Expression Trees 來根據字串取出對應的物件成員(欄位或屬性)的值。

以下是一個使用 Reflection 的簡單範例,可從字串取得物件欄位的值:
*/
public class B
{
	public int intResult;
	public B()
	{
	    intResult=100;
	}
}
public class A
{
    public int a;
    public int b;
    public B B1=new B();
}

public class Program
{
    public static void Main()
    {
        A obj = new A { a = 10, b = 20 };

        Console.WriteLine(GetFieldValueByName(obj, "a")); // Output: 10
        Console.WriteLine(GetFieldValueByName(obj, "b")); // Output: 20
	Console.WriteLine(GetFieldValueByName(obj.B1, "intResult")); // Output: 100
	Console.WriteLine(GetFieldValueByName(obj.B1, "intResul")); // null
	Console.WriteLine("End");
    }

    public static object? GetFieldValueByName(object obj, string fieldName)
    {
        if (obj == null || string.IsNullOrWhiteSpace(fieldName))
            return null;

        // BindingFlags to access public instance fields
        var field = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.Public);

        if (field == null)
            return null;

        return field.GetValue(obj);
    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *