帮助理解将数据传输到另一个类的本质。 所以,Silverlight应用程序。我有页面Home.xaml(和它的代码隐藏Home.xaml.cs)。有按钮。当我点击按钮时,执行以下代码:
Home.xaml.cs
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog opendialog = new OpenFileDialog();
opendialog.Multiselect = true;
bool? dialogResult = opendialog.ShowDialog();
if (dialogResult.HasValue && dialogResult.Value)
{
Stream fileStream = opendialog.File.OpenRead();
StreamReader reader = new StreamReader(fileStream);
............
这里我需要像 reader 这样的数据,因为我希望这个数据流(阅读器)发送到一些完全另一个类(例如,一个 DataProccess.cs ):
DataProccess.cs :
namespace SilverlightApplication1.Models
{
public static class DataProcess
{
{
}
}
将使用正则表达式处理数据流( reader 来自Home.xaml.cs),输出数据将放入集合List<>。
如何实现它。我很乐意为您提供几行代码? :)
修改后的代码:
Home.xaml.cs:
private void Button_Click(object sender, EventArgs e)
{
OpenFileDialog opendialog = new OpenFileDialog();
opendialog.Multiselect = true;
bool? dialogResult = opendialog.ShowDialog();
if (dialogResult.HasValue && dialogResult.Value)
{
Stream fileStream = opendialog.File.OpenRead();
var processor = new Processor();
ICollection<object> results = processor.Process(fileStream);
}
}
Processor.cs
public class Processor
{
public ICollection<object> Process(Stream stream)
{
StreamReader reader = new StreamReader(stream);
string pattern = @"set vrouter ""([\w-]+)""";
while (!reader.EndOfStream)
{
var matches =
Regex.Matches(reader.ReadToEnd(), pattern)
.Cast<Match>().Where(m => m.Success)
.Select(m => m.Groups[1].Value)
.Distinct();
foreach (var match in matches)
{
var val = match + Environment.NewLine;
return new Collection<object>().Add(val);; //here error
}
}
//return new Collection<object>(val);
}
}
此类错误: Error1 /无法将类型'void'隐式转换为'System.Collections.Generic.ICollection'
答案 0 :(得分:1)
创建一个将处理结果的新类
public class Processor
{
public ICollection<object> Process(Stream stream)
{
StreamReader reader = new StreamReader(stream);
// do stuff
return new Collection<object>();
}
}
然后创建它的实例并调用Process方法
Stream fileStream = opendialog.File.OpenRead();
var processor = new Processor();
ICollection<object> results = processor.Process(fileStream);