如何从另一个类构造一个类中的对象

时间:2012-09-29 13:35:27

标签: c# wpf c#-4.0 object c#-3.0

我在“FileData.cs”文件中声明了属性。我想为另一个类“PdfMergerViewModel.cs”中的每个属性赋值。

FileData.cs

        public class FileData
        {
        private BatchData _batch;
        public FileData(BatchData batch)
        {
            this._batch = batch;
        }

        public string FileName { get; set; }
        public string VersionNormalizedFileName { get; set; }
        public string OrderNumber { get; set; }
        public DateTime OrderDate { get; set; }

        public string Metadata { get; private set; }
        public bool IsDeleted { get; set; }
        public string FilePath { get; set; }

        public string Centerpoint { get; set; }
        public string BatchID { get; set; }
        public string RegionalPrefix { get; set; }
        public string City { get; set; }
        public string FunctionLocation { get; set; }
        public string KeyMap { get; set; }
        public string State { get; set; }
        public string StreetNumber { get; set; }
        public string StreetName { get; set; }
        public string UnitNumber { get; set; }
        public string SendToGIS { get; set; }
        public string PipeBeforeFilename { get; set; }

        public IList<FileData> VersionFiles
        {
            get
            {
                return _batch.Files.Where(x => x.VersionNormalizedFileName == FileName && !x.IsDeleted).ToList();
            }
            private set { }
        }

PdfMergerViewModel.cs

        FileData fd = new FileData(new BatchData());
        void createOutputBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            using (StreamReader sr = File.OpenText("D:/data.txt"))
            {
                String input;

                while ((input = sr.ReadLine()) != null)
                {
                    string[] stringArray = input.Split(',');
                    for (int i = 0; i < stringArray.Count() - 1; i++)
                    {

                    }
                }
            }
        }

我需要将“fd”对象放在for循环中,并为“FileData.cs”中的每个属性赋值。我不知道如何赋值。给我一个解决方案。感谢。

“Data.Txt”文件中存在多行。 “Data.txt”文件中的一行如下所示:

"Centerpoint - Arkansas (Fixed)","Centerpoint SO - Arkansas","{$DOCUMENT ID}","61||","{$BATCH ID}","32601","{$REGIONAL PREFIX}","E","CITY","CUSHING","DATE","05/25/1945","FUNCTION LOCATION","X-SVCS","KEY MAP","","ORDER NUMBER","","STATE","AR","STREET NUMBER","819","STREET NAME","E BROADWAY","UNIT NUMBER","","SEND TO GIS","X","{$PIPE BEFORE FILENAME}","||","\\HOUKOFAX01\Client\Centerpoint Arkansas\7_9_2012\32601\819 E BROADWAY.pdf"

以前使用“词典”。现在我们正在转向面向对象的方法。当字典项存在时,使用以下代码。现在,我需要使用面向对象的方法来分配“FileData.cs”类中的值,而不是字典。 使用词典项目的代码:

            Dictionary<string, string> item = new Dictionary<string, string>();
            for (int i = 0; i < stringArray.Count() - 1; i++)
            {
                item.Add(RemoveQuote(stringArray[i]), RemoveQuote(stringArray[i + 1]));
                i++;
            }

而不是字典,“fd”对象,我需要分配值。我不知道如何赋值。给我一个解决方案。感谢。

3 个答案:

答案 0 :(得分:3)

好吧,假设你在文本文件中有属性的名称和值,你可以尝试使用反射:

PropertyInfo propertyInfo = fd.GetType().GetProperty(propertyName);
propertyInfo.SetValue(fd, Convert.ChangeType(propertyValue, propertyInfo.PropertyType), null);

修改

如果您没有该属性的名称,那么它至少应按已知顺序组织,否则无法动态设置属性。

如果按已知顺序,您可以检索FileData属性并对其进行操作以使其与文本文件的顺序相同。

PropertyInfo[] propertyInfos = typeof(FileData).GetProperties(BindingFlags.Public);

//Possible Sort

foreach (PropertyInfo propertyInfo in propertyInfos)
{

}

答案 1 :(得分:0)

FileData fd = new FileData(new BatchData());
void createOutputBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    using (StreamReader sr = File.OpenText("D:/data.txt"))
    {
       String input;    
       while ((input = sr.ReadLine()) != null)
       {
            string[] stringArray = input.Split(',');
            PropertyInfo[] props = typeof (FileData).GetProperties();
            for (int i = 0; i < stringArray.Count() - 1; i++)
            {
                  props[i].SetValue(fd, stringArray[i]);
            }
       }
   }
}

P.S。不要忘记添加对System.Reflection的引用。

/////////////////////////////////////////////// ///////////////////////编辑////////////////////////// ////////////////////////////////////////////

嗯,我认为,最正确的解决方案是首先检查您的财产是什么类型,然后再进行分配。您可以使用if声明:

...
for (int i = 0; i < stringArray.Count() - 1; i++)
{
    if(props[i].GetValue(m) is DateTime)
    {
        props[i].SetValue(m, DateTime.Parse(stringArray[i]));
    }
    else
    {
        if(props[i].GetValue(m) is bool)
        {
            props[i].SetValue(m, stringArray[i].Equals("true", StringComparison.OrdinalIgnoreCase));
        }
        else
        {
             props[i].SetValue(m, stringArray[i]);
        }
    }
}
...

或者更优雅,特别是如果您的班级中有超过3种不同的类型,switch

...
for (int i = 0; i < stringArray.Length; i++)
{
    object type = props[i].PropertyType;
    switch(type.ToString())
    {
         case "System.String": props[i].SetValue(m, stringArray[i]); break;
         case "System.DateTime": props[i].SetValue(m, DateTime.Parse(stringArray[i])); break;
         case "System.Boolean": props[i].SetValue(m, stringArray[i].Equals("true", StringComparison.OrdinalIgnoreCase));break;
     }
}
...

注意:正如您所看到的,您应该使用type.ToString()语句,因为switch需要整数类型的值,props[i].GetType()props[i].PropertyType不是这样。

答案 2 :(得分:0)

首先,你需要一个List(Of FileData)来保存你从文件转换的每一行的内存,而不仅仅是一个FileData对象。 然后你应该找到data.txt中的read read和slipt之间的映射以及FileData的单个属性。

    List<FileData> listOfData = new List<FileData>();
    void createOutputBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
    { 
        using (StreamReader sr = File.OpenText("D:/data.txt")) 
        { 
            String input; 

            while ((input = sr.ReadLine()) != null) 
            { 
                FileData fd = new FileData(new BatchData()); 
                string[] stringArray = input.Split(','); 
                for (int i = 0; i < stringArray.Length - 1; i+=2) 
                { 
                     switch(stringArray[i])
                     {
                          case "{$BATCH ID}":
                             fd.BatchID = stringArray[i+1];
                             break;
                          // Other properties follow ..... 
                          case ......
                     }
                } 
                listOfData.Add(fd);
            } 
        } 
    }