【问题标题】:JS like enumaration in C#JS 喜欢 C# 中的枚举
【发布时间】:2016-09-07 09:19:54
【问题描述】:

在 JavaScript 中,我可以在每个单元格中有一个不同对象的数组,并且在枚举它时,每个单元格将被视为对象,而不是集合的底层公共对象。

假设我有 2 个对象:

class car
{
    public color;
    ...
}

class paint
{
    public color;
    ...
}

有没有类似枚举的语法

car beemer;
paint panda;
...
foreach (thing in [beemer, panda])
{
    thing.color = "red";
}

在 C# 中?

【问题讨论】:

  • 您能否提供一个您想在 C# 中模仿的 JavaScript 代码的完整示例?
  • [beemer, panda] 只是一个数组的 JS。 C# 数组?
  • 对这种事情使用interface
  • @DavidG 对象在黑盒 dll 中
  • @DvS 如何定义一个接受不同对象作为单元格的数组?

标签: c# dynamic enumeration


【解决方案1】:

好吧,如果你真的想要,你可以使用动态类型:

public class Paint
{
    public string Color { get; set; }
}

public class Car
{
    public string Color { get; set; }
}

...

var objects = new object[]
{
    new Car { Color = "Red" },
    new Panda { Color = "Black" }
};
foreach (dynamic value in objects)
{
    Console.WriteLine(value.Color);
}

但是更常规的做法是声明一个带有你想要的属性的接口,然后让所有相关的类型都实现这个接口:

public interface IColored
{
    string Color { get; set; }
}

public class Paint : IColored
{
    public string Color { get; set; }
}

public class Car : IColored
{
    public string Color { get; set; }
}

...

var objects = new IColored[]
{
    new Car { Color = "Red" },
    new Panda { Color = "Black" }
};
foreach (IColored value in objects)
{
    Console.WriteLine(value.Color);
}

这是:

  • 更高效
  • 更安全,因为您在编译时就知道,您迭代的每个值都有一个 Color 属性。

【讨论】:

  • 如果我将对象数组中的一个单元格视为动态的,它会给我自定义对象的所有原始属性吗?
  • @SharonJDDorot:是的 - 数组的值只是对对象的引用......
  • 给我一个编译错误:找不到编译动态表达式所需的一种或多种类型。您是否缺少参考资料?”
  • @SharonJDDorot:听起来您可能没有所需的所有参考资料,例如Microsoft.CSharpSystem.Dynamic(根据记忆......可能是错误的)。我们对您正在构建的项目类型、您正在使用的框架的版本、您正在使用的 Visual Studio 的版本等一无所知,这无济于事...但是搜索该错误消息,您会得到很多点击,例如stackoverflow.com/questions/11725514
【解决方案2】:

如果你用接口上定义的颜色属性实现一个接口就可以实现这个。

public interface IHasColor 
{
  string color { get; set; }
}

public class car : IHasColor
{
    public color { get; set; }
    ...
}

foreach (IHasColor thing in new IHasColor[] { beemer, panda })
{
    thing.color = "red";
}

【讨论】:

  • 这些对象来自一个黑盒 dll
  • 那么继承可以解决这个问题,创建你自己的类版本并在那里实现接口
猜你喜欢
  • 1970-01-01
  • 2020-12-16
  • 2016-12-31
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2016-03-13
  • 2020-11-23
  • 2010-11-26
相关资源
最近更新 更多