【问题标题】:Array like initialization class C#像初始化类 C# 一样的数组
【发布时间】:2017-10-19 11:21:26
【问题描述】:

可能是个愚蠢的问题,但我想像这样初始化我的对象数组:

FooBar[] fooBars = new FooBars[]
{
    {"Foo", "Bar"},
    {"Foo", "Bar"}
};

FooBar 在哪里:

public class FooBar
{
    public string foo;
    public string bar;
}

我尝试过从 CollectionBase 继承并添加 Add(string) 方法或 string[] 运算符,但这些都不起作用:/

【问题讨论】:

  • Ofc 字典是这样工作的: Dictionary dic = new Dictionary() {{"foo", "bar"}};
  • 如果你已经标记了一个FooBars数组,那么你还需要用FooBars的实例来填充它,所以你必须做new Foobar(),然后填写foo和@987654327 @ 特性。然而,更好的方法是在 FooBar 构造函数中传递它们。此外,如果您想使用字符串对,请考虑使用字典。
  • 如果您认为您缺少来自 IEnumerable 的继承 - 请参阅此答案:stackoverflow.com/a/9570300/1632576

标签: c# arrays initialization


【解决方案1】:

这就是你要找的吗? 我不明白你在问什么。

如果你愿意,可以在fiddle 中玩一下。

public class FooBar
{
    public FooBar(string foo, string bar)
    {
        this.foo = foo;
        this.bar = bar;
    }

    public string foo;
    public string bar;
}

public static void Main(String[] args)
{
    FooBar[] fooBars = new FooBar[] {
        new FooBar("Foo", "Bar"), 
        new FooBar("Foo", "Bar")
    };
}

【讨论】:

    【解决方案2】:

    你可以通过给类 FooBar 一个隐式构造函数来作弊(需要最新版本的 C# 来支持元组):

    public class FooBar
    {
        public string foo;
        public string bar;
    
        public static implicit operator FooBar((string, string) init)
        {
            return new FooBar{ foo = init.Item1, bar = init.Item2 };
        }
    }
    

    然后这样的代码就可以工作了:

    var fooBars = new FooBar[]
    {
        ("Foo1", "Bar1"),
        ("Foo2", "Bar2")
    };
    

    或

    FooBar[] fooBars = 
    {
        ("Foo1", "Bar1"),
        ("Foo2", "Bar2")
    };
    

    然后:

    foreach (var fooBar in fooBars)
        Console.WriteLine($"foo = {fooBar.foo}, bar = {fooBar.bar} ");
    

    这似乎与您的目标非常接近(尽管使用括号而不是大括号)。

    但通常您只需按照其他答案使用 new FooBar("Foo", "Bar") 语法。

    【讨论】:

    • 这很有帮助,不是我想要的,但看起来很酷;)
    • @blackmaciek 请注意,这不是一个非常有效的解决方案,因为您将为每次调用 FooBar 构造函数构建一个临时元组,如果您使用普通的 @ 则没有必要这样做987654327@ 语法。
    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多