gpt4 book ai didi

c# - 如何声明具有匿名类型的字段 (C#)

转载 作者:行者123 更新时间:2023-11-30 19:22:34 25 4
gpt4 key购买 nike

在下面的代码中,如何将 myLine 声明为公共(public)(全局)变量?问题是我不能使用关键字“var”。

    public static IEnumerable<string> ReadLines(StreamReader reader)
{
while (!reader.EndOfStream)
{
yield return reader.ReadLine();
}
}

private void Filter1(string filename)
{
using(var writer = File.CreateText(Application.StartupPath + "\\temp\\test.txt"))
{
using (var reader = File.OpenText(filename))
{
int[] Ids = { 14652, 14653, 14654, 14655, 14656, 14657, 14658, 14659, 14660 };
var myLine = from line in ReadLines(reader)
where line.Length > 1
let id = int.Parse(line.Split('\t')[1])
where Ids.Contains(id)
let m = Regex.Match(line, @"^\d+\t(\d+)\t.+?\t(item\\[^\t]+\.ddj)")
where m.Success == true
select new { Text = line, ItemId = id, Path = m.Groups[2].Value };


foreach (var id in myLine)
{
writer.WriteLine("Item Id = " + id.ItemId);
writer.WriteLine("Path = " + id.Path);
writer.WriteLine("\n");
}

}
}
}

我想这样做,因为我必须找到一种方法来访问那个 ienumerable 供以后使用。

最佳答案

问题在于它使用的是匿名类型,您不能在字段声明中使用它。

修复方法是编写一个具有相同成员的命名类型,并在您的查询中使用该类型。如果您希望它具有与您的匿名类型相同的行为,它应该:

  • 在构造函数中取所有值
  • 不可变,公开只读属性
  • 覆盖 EqualsGetHashCodeToString
  • 密封

可以只使用 Reflector 反编译代码,但最终会得到您并不真正需要的通用类型。

这个类看起来像这样:

public sealed class Foo
{
private readonly string text;
private readonly int itemId;
private readonly string path;

public Foo(string text, int itemId, string path)
{
this.text = text;
this.itemId = itemId;
this.path = path;
}

public string Text
{
get { return text; }
}

public int ItemId
{
get { return itemId; }
}

public string Path
{
get { return path; }
}

public override bool Equals(object other)
{
Foo otherFoo = other as Foo;
if (otherFoo == null)
{
return false;
}
return EqualityComparer<string>.Default.Equals(text, otherFoo.text) &&
return EqualityComparer<int>.Default.Equals(itemId, otherFoo.itemId) &&
return EqualityComparer<string>.Default.Equals(path, otherFoo.path);
}

public override string ToString()
{
return string.Format("{{ Text={0}, ItemId={1}, Path={2} }}",
text, itemId, path);
}

public override int GetHashCode()
{
int hash = 17;
hash = hash * 23 + EqualityComparer<string>.Default.GetHashCode(text);
hash = hash * 23 + EqualityComparer<int>.Default.GetHashCode(itemId);
hash = hash * 23 + EqualityComparer<string>.Default.GetHashCode(path);
return hash;
}
}

您的查询最后会更改为:

select new Foo(line, id, m.Groups[2].Value)

关于c# - 如何声明具有匿名类型的字段 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/964334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com