C# 匿名对象、动态属性
以下代码基于 Unity, 放置在 Editor文件夹下
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
public class EditorTest : Editor {
[MenuItem("Tools/EditorTest", true)]
private static bool ValidateMenuItem() {
return !EditorApplication.isPlaying;
}
[MenuItem("Tools/EditorTest")]
private static void Test() {
if (EditorApplication.isPlaying) return;
Debug.Log("== Tools/EditorTest ==");
// 匿名对象
var obj = new { a = 1, b = 2 };
GetProps(obj);
// 动态属性,使用 System.Dynamic.ExpandoObject 类实现
dynamic dyObj = new System.Dynamic.ExpandoObject();
dyObj.a = 3;
dyObj.b = 4;
GetDyProps(dyObj);
}
private static T CastAnonymous<T>(object anonymous, T anonymousType) {
return (T)anonymous;
}
private static void GetProps(object arg) {
// 利用泛型特性访问属性
var obj = CastAnonymous(arg, new { a = 0, b = 0 });
Debug.Log($"obj.a:{obj.a}, obj.b:{obj.b}"); // output: obj.a:1, obj.b:2
// 利用反射机制访问属性
var argType = arg.GetType();
var a = argType.GetProperty("a").GetValue(arg);
var b = argType.GetProperty("b").GetValue(arg);
Debug.Log($"a:{obj.a}, b:{obj.b}"); // output: a:1, b:2
}
private static void GetDyProps(dynamic dyObj) {
Debug.Log($"dyObj.a:{dyObj.a}, dyObj.b:{dyObj.b}"); // output: dyObj.a:3, dyObj.b:4
}
}
#endif