這一直使我瘋狂了一段時間。我有一個包含其他類的類。我需要循環遍歷第一類尋找typeof第二類然後檢索字段的值。從班級中的班級獲取字段值
下面的代碼就行了
Console.WriteLine(field.GetValue(mFC.field.secondClassString));
明顯失敗,因爲這不是一個有效的字段。可能我會以這種錯誤的方式去做 - 有什麼想法?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
MyFirstClass mFC = new MyFirstClass();
FieldInfo[] fI = mFC.GetType().GetFields();
foreach (FieldInfo field in fI)
{
if (field.FieldType.Name == "MySecondClass")
{
//get the fields
Console.WriteLine(field.GetValue(mFC.field.secondClassString));
}
}
}
}
class MyFirstClass
{
public MySecondClass firstMSC = new MySecondClass("First Instance");
public MySecondClass secondMSC = new MySecondClass("Second Instance");
public string firstClassString = "I'm from the first class";
public int firstClassInt = 5;
}
class MySecondClass
{
public MySecondClass(string input)
{
this.secondClassString = input;
}
public string secondClassString;
public int secondClassInt = 10;
}
}
那就是那個!需要向內部階層施放。謝謝 – user1156000
我正在嘗試將整個場轉換回表面物體。我該如何做到這一點.. MySecondClass newClass =(MySecondClass).field ..... – user1156000
MySecondClass c =(MySecondClass)field.GetValue(mFC);你可以做到這一點 – Bunny