1

「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」ファイルの1行は次のようになります。

"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」オブジェクトの代わりに、値を割り当てる必要があります。値の割り当て方がわかりません。解決策を教えてください。ありがとう。

4

3 に答える 3

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)
{

}
于 2012-09-29T13:51:20.610 に答える
0

最初に、1 つの FileData オブジェクトだけでなく、ファイルから変換するすべての行をメモリに保持する List(Of FileData) が必要です。次に、data.txt から読み取られてスリップされた行と、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);
            } 
        } 
    } 
于 2012-09-29T14:16:57.973 に答える
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]);
            }
       }
   }
}

PSへの参照を追加することを忘れないでください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()ステートメントを使用する必要があります。switchprops[i].GetType()props[i].PropertyType

于 2012-09-29T14:12:03.030 に答える