我知道这是一个愚蠢的问题,它可能很容易,但我正盯着屏幕看起来像3个小时,我似乎仍然无法弄明白。知道如何缩短这段代码吗?我的班级Car.cs中有public enum Type
和public enum Size
。
Car car1 = new Car((CarType)0, (Size)0);
Car car2 = new Car((CarType)0, (Size)1);
Car car3 = new Car((CarType)0, (Size)2);
Car car4 = new Car((CarType)1, (Size)0);
Car car5 = new Car((CarType)1, (Size)1);
Car car6 = new Car((CarType)1, (Size)2);
Car car7 = new Car((CarType)2, (Size)0);
Car car8 = new Car((CarType)2, (Size)1);
Car car9 = new Car((CarType)2, (Size)2);
编辑:我用这样的方法打印它们
Group1Print(car1, car2, car3);
Group2Print(car4, car5, car6);
Group3Print(car7, car8, car9);
答案 0 :(得分:1)
试试这个:
var cars = new List<Car>();
foreach (Type type in Enum.GetValues(typeof(Type)))
{
foreach (Size size in Enum.GetValues(typeof(Size)))
{
cars.Add(new Car() {Size = size, Type = type});
}
}
或LINQ版本:
var cars = (from Type type in Enum.GetValues(typeof(Type))
from Size size in Enum.GetValues(typeof(Size))
select new Car() {Size = size, Type = type}).ToList();
答案 1 :(得分:-1)
var cars = Enumerable.Range(0, 9)
.Select(i => new Car((Type)(i / 3), (Size)(i % 3)))
.ToArray();
答案 2 :(得分:-1)
我尝试过这样的事情。似乎是一个有效的答案。谢谢你的帮助。
// Low level datalink class
class RS485
{
public:
void send(const char *data) {
// datalink function to send data using RS485
printf("RS485: %s \n", data);
}
};
class I2C
{
public:
void send(const char *data) {
// datalink function to send data using I2C
printf("I2C: %s \n", data);
}
};
class BT
{
public:
void send(const char *data) {
// datalink function to send data using Bluetooth
printf("BT %s \n", data);
}
};
// Protocol class
template<typename Comm>
class MODBUS
{
public:
MODBUS(Comm *c) { _c = c; }
void send(const char *data) {
printf("MODBUS\n");
_c->send(data);
}
private:
Comm *_c;
};
// Protocol class
template<typename Comm>
class TCP
{
public:
TCP(Comm *c) { _c = c; }
void send(const char *data) {
printf("TCP\n");
_c->send(data);
}
private:
Comm *_c;
};
int main() {
// Modbus over I2C
I2C *i2c = new I2C();
MODBUS<I2C> *mb_i2c = new MODBUS<I2C>(i2c);
mb_i2c->send("Data ...");
// Modbus over RS485
RS485 *rs = new RS485();
MODBUS<RS485> *mb_rs = new MODBUS<RS485>(rs);
mb_rs->send("Data ...");
// Tcp over Modbus over RS485
TCP< MODBUS<RS485> > *tcp_modbus_rs = new TCP< MODBUS<RS485> >(mb_rs);
tcp_modbus_rs->send("Data ...");
return 0;
}