【问题标题】:Reflection issue in WinRTWinRT 中的反射问题
【发布时间】:2023-04-09 13:03:01
【问题描述】:

我在将 WP7 应用程序移植到 win8 商店应用程序时遇到问题...

我运行此代码从 XML 文件中的元素填充字段:

Venue lv = new Venue();

            foreach (var t in Fields)
            {
                foreach (var f in t.Elements())
                {
                    lv.SaveData(f.Attribute("name").Value, f.Value, lv);
                }
            }

数据类:

 public class Venue //: INotifyPropertyChanged
    {
        public string updated_at { get; set; }
        public string name { get; set; }
        public string authority { get; set; }
        public string organisation { get; set; }
        public string control_type { get; set; }
    }

运行 SaveData 方法:

public void SaveData(string field, string value, Venue v)
        {

            foreach (MemberInfo mi in v.GetType().GetTypeInfo().GetMembers())
            {
                if (mi.MemberType == MemberTypes.Property)
                {
                    PropertyInfo pi = mi as PropertyInfo;

                    if (pi.Name == "Coordinate")
                        continue;

                    if (pi.Name == field)
                    {
                        pi.SetValue(v, value, null);
                    }
                }
            }
        }

问题是,GetMembers 定义在 WinRT 中不存在,因此要么需要找到替代方案来公开相同的属性,要么必须找到重写系统的方法。

这段代码不是我自己写的,但我可以理解它在做什么。我对反思不是太熟悉,除了我刚刚阅读的基本介绍 任何快速修复

【问题讨论】:

  • 你试过GetType().GetMembers()(不使用GetTypeInfo)吗?
  • 嗨,是的,它也不存在。

标签: c# windows-runtime windows-store-apps .net-4.5


【解决方案1】:

GetType 是一种扩展方法。您需要包含反射命名空间:

using System.Reflection;

对于您的 SaveData 方法,您可以执行以下操作:

public void SaveData(string field, string value, Venue v)
{
    var typeinfo = v.GetType().GetTypeInfo();
    var pi = typeinfo.GetDeclaredProperty(field);

    if (pi != null && pi.Name != "Coordinate")
       pi.SetValue(v, value);
}

您可能想要做一些比上面的代码更好的错误检查。例如确保vpi.Name 不为空。

【讨论】:

  • 好像是这个!很简单!
猜你喜欢
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多