gpt4 book ai didi

c# - 一个参数的多个构造函数

转载 作者:太空狗 更新时间:2023-10-29 20:53:12 28 4
gpt4 key购买 nike

所以,在学校里,我们接到了一项任务,要用 OOP 制造汽车,直到现在它都非常简单直接。但是现在我需要创建四个构造函数,一个没有参数,两个有一个参数,一个有两个参数。

据我所知,重载的工作方式是检查您提供给它的参数数量,然后检查它必须使用哪个构造函数。由于两个构造函数相同,都接受整数,只有一个需要改变数量或档位,另一个需要改变最大速度。

有没有办法在不传递额外参数的情况下做到这一点?

最佳答案

As far as I know the way overloading works is that it checks the amount of parameters you supply it with and then checks which constuctor it has to use.

不,重载不仅仅基于参数的数量 - 它也基于它们的类型

但是:

As two of the constructors are the same, both accepts strings

这是一个问题。您不能像这样声明两个构造函数:

public Foo(string x)
{
}

public Foo(string y)
{
}

就重载而言,这些签名会发生冲突。

我建议使用公共(public)静态 工厂方法,这样您就可以指定要创建的内容:

public static Foo FromGears(string gears)
{
return new Foo(...);
}

public static Foo FromMaximumSpeed(string maxSpeed)
{
return new Foo(...);
}

然后您可能会有一个接受两个值的构造函数,并在您从工厂方法调用构造函数时默认缺少一个值。

但是,您的描述中还有另外两个奇怪之处:<​​/p>

  • 您将字符串 用于两个听起来应该是数字(或者可能是一个数字,一个数字和单位)的值
  • 您正在谈论声明构造函数,但随后使用“更改”一词,就好像它们要更改现有实例一样。这没有意义 - 构造函数用于创建对象。

编辑:好的,现在我们知道的更多了,这就是我的意思:

public class Car
{
private const int DefaultGears = 5;
private const int DefaultTopSpeed = 180;

private readonly int gears;
private readonly int topSpeed;

public Car(int gears, int topSpeed)
{
this.gears = gears;
this.topSpeed = topSpeed;
}

public static Car CreateWithGears(int gears)
{
return new Car(gears, DefaultTopSpeed);
}

public static Car CreateWithTopSpeed(int topSpeed)
{
return new Car(topSpeed, DefaultGears);
}
}

请注意,您可以在 C# 4 中也为此使用可选参数和命名参数:

public class Car
{
public const int DefaultGears = 5;
public const int DefaultTopSpeed = 180;

private readonly int gears;
private readonly int topSpeed;

public Car(int gears = DefaultGears, int topSpeed = DefaultTopSpeed)
{
this.gears = gears;
this.topSpeed = topSpeed;
}
}

然后:

Car car = new Car(gears: 4);
Car car = new Car(topSpeed: 30);

不过,我一般不会推荐 - 当然,当您对这门语言还比较陌生时,肯定不会。可选参数有各种微妙之处。

关于c# - 一个参数的多个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9540905/

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