c# - 反射:获取/设置属性的PropertyType的属性值
问题描述
所以我仍然在将我的读取数据自动化到 UI 中(使用 Unity),情况是这样的:在 GameObject 上,我有一个脚本,我在其中存储变量/属性及其整齐排序的属性。我通过反射阅读它们,例如:
public void insertAllFromGameObject(GameObject target, List<Type> types)
{
var components = target.GetComponents<Component>();
foreach (var component in components)
{
if(types.Contains(component.GetType()))
{
var properties = component.GetType().GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
foreach(var p in properties)
{
Debug.Log("VALUE: "+p.GetValue(component, null));
这行得通。现在,假设我有一个属性,我想在它的类中达到峰值,列出它的属性,而不是在这个特定属性中设置的值,并可能针对这个属性一一修改它们。
我已经列出了清单,但无法弄清楚将什么作为参数传递给 GetValue。例子:
public void insertAllFromVariable(GameObject target, List<Type> types, string propertyName)
{
var components = target.GetComponents<Component>();
foreach (var component in components)
{
if(types.Contains(component.GetType()))
{
var property = component.GetType().GetProperty(propertyName);
var propertysProperties = property.PropertyType.GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
foreach(var p in propertysProperties)
{
Debug.Log("VALUE: "+p.GetValue(component, null));
最后一行是一个问题,因为我当然不是在“组件”中寻找它(而是在组件内的属性中) - 但是我应该传递什么以便它反映我的变量值?
解决方案
修改了您的代码,确保我没有运行代码,但您应该清楚概念:
public void insertAllFromVariable(GameObject target, List<Type> types, string propertyName)
{
var components = target.GetComponents<Component>();
foreach (var component in components)
{
if (types.Contains(component.GetType()))
{
PropertyInfo property = component.GetType().GetProperty(propertyName);
object theRealObject = property.GetValue(component);
PropertyInfo[] propertysProperties = theRealObject.GetType().GetProperties().Where(t => t.GetCustomAttributes<ListableAttribute>().Count() > 0);
foreach (PropertyInfo p in propertysProperties)
{
Debug.Log("VALUE: " + p.GetValue(theRealObject));
推荐阅读
- python - 从深度嵌套的 JSON 对象回填每日表
- properties - AEM Sling 从模型内更新属性
- flutter - 如何在 Flutter 中更改 DropdownMenuItem?(断言失败)
- c# - Httpclient.SendAsync loads StreamContent into memory before sending it to the server
- python - 在 Python 终端中显示表情符号字符
- javascript - 如何导入 Lodash 以获得最小的构建尺寸
- c++ - 如何使用 nlohmann c++ 删除嵌套的 json 数据
- excel - VBA 代码适用于除最后一行之外的每一行
- javascript - React Typescript登录不发送请求但重新渲染主要组件
- database-design - 如何找到最小封面的数量?