简体   繁体   English

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

[英]How do I declare a Field with Anonymous Type (C#)

In the code below,how do I declare myLine as a public(global) variable? 在下面的代码中,如何将myLine声明为公共(全局)变量? The problem is that I can't use the keyword "var". 问题是我不能使用关键字“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");
                }

            }
        }
    }

I want to do it ,because I have to find a way to gain access to that ienumerable for later use. 我想这样做,因为我必须找到一种方法来获取对该数量的访问以供以后使用。

The trouble is that it's using an anonymous type, which you can't use in a field declaration. 麻烦的是它使用的是匿名类型,你不能在字段声明中使用它。

The fix is to write a named type with the same members, and use that type in your query. 修复方法是编写具有相同成员的命名类型,并在查询中使用该类型。 If you want it to have the same behaviour as your anonymous type, it should: 如果您希望它与您的匿名类型具有相同的行为,它应该:

  • Take all the values in the constructor 获取构造函数中的所有值
  • Be immutable, exposing read-only properties 是不可变的,暴露只读属性
  • Override Equals , GetHashCode and ToString 覆盖EqualsGetHashCodeToString
  • Be sealed 密封

You could just use Reflector to decompile the code, but then you'd end up with a generic type which you don't really need. 可以使用Reflector来反编译代码,但是你最终会得到一个你并不真正需要的泛型类型。

The class would look something like: 该类看起来像:

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;
    }
}

Your query would just change at the end to: 您的查询最后会更改为:

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

Instead of using an anonymous class with the new keyboard, define a class explicitly with a Text, ItemId, etc. Then the type would be IQueryable<MyClass>. 不使用带有键盘的匿名类,而是使用Text,ItemId等显式定义类。然后类型将是IQueryable <MyClass>。 Use that instead of the var keyword. 使用它而不是var关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不创建实例的情况下声明 C# 匿名类型? - How do I declare a C# anonymous type without creating an instance of it? 如何在C#匿名类型中声明“Key”字段? - How do I declare “Key” fields in C# anonymous types? 如何将 C# 匿名类型序列化为 JSON 字符串? - How do I serialize a C# anonymous type to a JSON string? 是否可以使用变量/动态字段集在C#中声明匿名类型? - Is it possible to declare an anonymous type in C# with a variable/dynamic set of fields? 如何在C#中使用变量的值作为键来声明匿名类型? - how to declare anonymous type using a variable's value as key in c#? C#如何在方法参数列表中声明lambda或匿名函数类型? - C# How to declare lambda or anonymous function type in method argument list? C#-如何获取匿名类型,然后使用相同的选择器创建对象? - C# - How do I get an anonymous type and then use the same selector to create an object? c# - 如何检查属性是否存在于c#中的动态匿名类型? - How do I check if a property exists on a dynamic anonymous type in c#? 如何将JSON对象数组反序列化为C#匿名类型? - How do I deserialize an array of JSON objects to a C# anonymous type? 如何将变量声明为与方法在c#中返回的数据类型相同的数据类型? - How do I declare a variable as the same data type as the method returns in c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM