带字符串的字符串的嵌套属性错误

时间:2014-01-06 07:51:59

标签: c# .net string properties

我有两个问题

  1. 有没有办法初始化一个类和所有子类,所以代码中新项的所有元素都为null?

  2. 如何处理类型项列表。 EmbeddedGenerator并停止错误

     Object reference not set to an instance of an object.
       at ConsoleApplication1.Program.SetProperty(String compoundProperty,
       Object target, String value)
       at ConsoleApplication1.Program.Main(String[] args)
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,
       String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile,
       Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run
       (ExecutionContext executionContext, ContextCallback callback,
        Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext
       executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
    

    (new System.Collections.Generic.Mscorlib_CollectionDebugView(((System.Collections.Generic.List)(target))))。Items [0] .id.id_high

  3. 示例“class1.properity1 = 1”

    我遇到了一个错误,这里是一个简短的控制台应用程序,概述了错误 我试图将id_high的值设置为1路径为generator.contents [0] .id.id_high

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using Items;
        using System.Reflection;
    
        namespace ConsoleApplication1
        {
         class Program
         {
          static List<SavedItem> items = new List<SavedItem>();
          static void Main(string[] args)
          {
           Items.SavedItem item = new Items.SavedItem();
           item.generator = new Items.Generator();
           item.generator.contents = new List<Items.EmbeddedGenerator>();
           item.generator.contents.Add(new Items.EmbeddedGenerator());
           item.generator.contents[0].id = new OnlineService.ItemId();
    
           SetProperty(".generator.contents[0].id.id_high", item, "1");
    
           items.Add(item);
          }
    
          //jon skeet's modified method
          public static void SetProperty(string compoundProperty, 
          object target, string value)
          {
           string[] bits = compoundProperty.Split('.');
           for (int i = 0; i < bits.Length - 1; i++)
           {
            if (bits[i].IndexOf('[') > 0)
            {
             bits[i] = bits[i].Substring(0, bits[i].IndexOf('['));
            }
    
            PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]);
            target = propertyToGet.GetValue(target, null); 
           }
           if (bits[bits.Length - 1].IndexOf('[') > 0)
           {
            bits[bits.Length - 1] = bits[bits.Length - 1].Substring
            (0, bits[bits.Length - 1].IndexOf('['));
            value = value.Trim('{', '}');
    
            PropertyInfo lstpropertyToSet = target.GetType().GetProperty(bits.Last());
            if (value != "null")
            {
    
             List<int> list = new List<int>();
             foreach (string s in value.Split(','))
             {
              list.Add(Int32.Parse(s));
             }
             lstpropertyToSet.SetValue(target, 
              Convert.ChangeType(list, lstpropertyToSet.PropertyType)
              , null);
            }
    
            return;
           }
           PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last());
           if (value != "null")
           {
            propertyToSet.SetValue(target,
             Convert.ChangeType(value, propertyToSet.PropertyType),
             null);
           }
           return;
          }
    
         }
        }
    
    
       //....Items has an id_high separate from program   
        namespace Items
        {
         public partial class SavedItem
         {
          public SavedItem() { }
          private Items.Generator _generator = null;
          [global::System.ComponentModel.DefaultValue(null)]
          public Items.Generator generator
          {
           get { return _generator; }
           set { _generator = value; }
          }
          //....
         }
         public partial class Generator 
         {
          public Generator() { }
          private System.Collections.Generic.List<EmbeddedGenerator> _contents = 
           new System.Collections.Generic.List<EmbeddedGenerator>();
          public System.Collections.Generic.List<EmbeddedGenerator> contents
          {
           get { return _contents; }
           set { _contents = value; }
          }
          //.....
         }
         public partial class EmbeddedGenerator
         {
          public EmbeddedGenerator() { }
    
          private OnlineService.ItemId _id;
          public OnlineService.ItemId id
          {
           get { return _id; }
           set { _id = value; }
          }
          //....
         }
        }
        //....onlineService has an id_high separate from ConsoleApplication1 and Items
        namespace OnlineService
        {
         public partial class ItemId 
         {
          public ItemId() { }
    
          private ulong _id_high;
          public ulong id_high
          {
           get { return _id_high; }
           set { _id_high = value; }
          }
         }
         //....
        }
    

    此代码将正常运行,直到它到达内容集合,回答第一个问题可能解决我的问题,但我认为不会,因为并非所有属性都需要一个值,如果有的话会导致问题。

    编辑: 添加此项有助于将属性添加到目标 但现在“不能将带有[]的索引应用于'object'类型的表达式  当您尝试制作目标时,请参阅第1项

    item.generator.contents.Add(new Items.EmbeddedGenerator());         item.generator.contents [0] .id = new OnlineService.ItemId();

1 个答案:

答案 0 :(得分:0)

尝试:

  1. 公开属性。

  2. 错误是因为“bits [i]”中的属性名称不存在 目标。您提供了错误的属性名称。通过有效 财产,它会工作。

    PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]);
    
    // bits[i] property doesnot exists in target.
    
    target = propertyToGet.GetValue(target, null); //here is the issues