给同一个数据参数相同的实例

编程入门 行业动态 更新时间:2024-10-23 15:28:06
本文介绍了给同一个数据参数相同的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个具有这种结构的文本文件:

I have a text file with such structure:

{A, B, C, D} {B, E, D} {C, A, F} ......

第一行表示起始位置,其他行表示目的地。例如:

The first row represents a start location and the others is destinations. Forexample:

A -> B, C, D B -> E, D C -> A, F

我有一个名为Location的基本类,我保存所有的位置和目的地。

I have a basic class called Location, where i save all the locations and destinations.

Location locA = new Location(); Location locB = new Location();

我有兴趣使用相同的实例位置而不为每个人创建一个新实例,例如:

I'm interested in using the same instance location without making a new instance for everyone, forexample like:

Connection(locA, locB)); Connection(locA, locC)); Connection(locA, locD)); Connection(locB, locE);

问题是当我分割我的文本文件时。我把第一行放在列表中。和目的地在另一个列表中。 :

The problem is when i'm splitting my text file. i'm putting the first row inside a list. and the destination in another list. :

DKLocations Startloc = new DKLocations(); DKLocations Destloc = new DKLocations(); List<DKLocations> DKLocations = new List<DKLocations>();

这是我的代码所以票价:

Here is my code so fare:

foreach (var line in File.ReadLines(@"routes.txt")) { foreach (Match oMatch in Regex.Matches(line, @"\{([^,]*)")) { ComboBox1.Items.Add(oMatch.Groups[1].Value); Startloc.Identifier = DKLocations.Count().ToString(); Startloc.LocationName.Add(oMatch.Groups[1].Value); DKLocations.Add(Startloc); var dest = Regex.Matches(line, @"\p{L}+") .Cast<Match>() .Skip(1) .Select(match => match.Value) .ToList(); var price = Regex.Matches(line, @"\d+") .Cast<Match>() .Select(match => match.Value) .ToList(); var destAndPrice = dest.Zip(price, (d, p) => new { dest = d, price = p }); foreach (var i in destAndPrice) { ListBox1.Items.Add(oMatch.Groups[1].Value + " to " + i.dest + " " + i.price + " kr." + DKLocations.Count().ToString()); } }

如何为目的地提供相同的实例作为拆分时的起始位置?

How to give the destination same instance as the start location when splitting?

推荐答案

听起来你想要记忆模式。

Sounds like you want the "memoizing" pattern.

在C#中,这通常是用字典完成的。例如:

In C#, this is usually done with a dictionary. E.g.:

Dictionary<string, Location> memos = new Dictionary<string, Location>();

然后在阅读数据时,先检查字典:

Then as you read the data, you check the dictionary first:

Location location; if (!memos.TryGetValue(locationId, out location)) { location = new Location(locationId); memos[locationId] = location; } // do stuff with location now

主要的是有一种方法来识别你想要的 Location 实例,然后将其用作字典中的键。

The main thing is to have a way to identify which Location instance you want, and then use that as the key in the dictionary.

更多推荐

给同一个数据参数相同的实例

本文发布于:2023-10-30 04:08:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541718.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   参数   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!