馬上注冊,結交更多好友,享用更多功能,讓你輕松玩轉社區。
您需要 登錄 才可以下載或查看,沒有帳號?注冊帳號
x
一、前言
上一章通過反射實現創建動態編輯欄,但是此時的編輯欄還并沒有和結構體數據關聯。本章將實現編輯欄中修改的數據將反饋到對應的結構體中,并最后通過序列化將結構體數據以文本的形式進行存儲 二、實現 1、FieldInfo.SetValue方法 將給定對象的字段設置為給定值,查閱了C#的官方文檔,上面的案例是這樣的 [C#] 純文本查看 復制代碼 using System;
using System.Reflection;
using System.Globalization;
public class Example
{
private string myString;
public Example()
{
myString = "Old value";
}
public string StringProperty
{
get
{
return myString;
}
}
}
public class FieldInfo_SetValue
{
public static void Main()
{
Example myObject = new Example();
Type myType = typeof(Example);
FieldInfo myFieldInfo = myType.GetField("myString",
BindingFlags.NonPublic | BindingFlags.Instance);
// Display the string before applying SetValue to the field.
Console.WriteLine( "\nThe field value of myString is \"{0}\".",
myFieldInfo.GetValue(myObject));
// Display the SetValue signature used to set the value of a field.
Console.WriteLine( "Applying SetValue(Object, Object).");
// Change the field value using the SetValue method.
myFieldInfo.SetValue(myObject, "New value");
// Display the string after applying SetValue to the field.
Console.WriteLine( "The field value of mystring is \"{0}\".",
myFieldInfo.GetValue(myObject));
}
}
/* This code example produces the following output:
The field value of myString is "Old value".
Applying SetValue(Object, Object).
The field value of mystring is "New value".
這段代碼在參數是類的對象的時候是毫無問題的,但是傳進來結構體變量的時候,就會出現沒有附上值的問題。這個主要是跟結構體是值類型,類是引用類型有關。 Fieldinfo.SetValue(object,object),里面的參數都是引用類型的,而結構體是指類型,在調用該方法傳結構體變量的時候,會將結構體賦值一份新的,然后在方法里面對新的值進行了修改,而傳進去原來的結構體并沒有任何改變。所以,在調用SetValue之前,先將結構體進行裝箱操作變成Object類型的變量,然后,在進行拆箱操作,將Object變量轉換成結構體變量。代碼如下: 我將這個方法進行了簡單的泛型處理,這樣保證不管是什么結構體或類都可以作為參數傳遞進來,并進行轉換。方法最后,返回的是一個Object類型的變量,對這個變量進行拆箱操作就可以了: 在每一個編輯欄的輸入框組建中都添加了編輯結束響應事件,保證每次對單個編輯框編輯的時候,結構體的數據都會得到修改如圖所示:當對單個編輯框進行修改的時候,右側的Inspector面板上的結構體字段的值也會相應的改變,在輸入錯誤的時候,還加入了相應的處理,出現輸入的值和字段類型不匹配則回到上一個輸入框的值,并且結構體不發生改變。
最后,將修改后的結構體變量的值存成文本文件:
[C#] 純文本查看 復制代碼 public static object SetValue_ReflectMethod<T>(T obj, string paramName, string paramValue)
{
//先裝箱 變成引用類型的
object tempObj = obj;
if (obj != null)
{
try
{
Type tempType = obj.GetType();
//設置字段
FieldInfo tempFI = tempType.GetField(paramName);
tempFI.SetValue(tempObj, Convert.ChangeType(paramValue, tempFI.FieldType));
//設置屬性
//PropertyInfo tempPI = tempType.GetProperty(paramName);
//tempPI.SetValue(tempObj, Convert.ChangeType(paramValue, tempPI.PropertyType), null);
}
catch (Exception e)
{
Debug.Log("編輯錯誤" + e.Message);
tempObj = null;
}
}
return tempObj;
}
三、總結
1、初步具備了根據結構體字段來動態創建編輯框的功能
2、可以在輸入框中對結構體的對應名稱字段進行修改,并且編輯框中還加入了錯誤輸入的處理
3、將結構體數據保存成Json文件
4、尚不具備對泛型的處理
未完待續。。。。。
工程案例地
|