【问题标题】:C# Class initialization with different arguments?具有不同参数的 C# 类初始化?
【发布时间】:2017-09-05 13:42:22
【问题描述】:

我有一个类,我用普通的public Class1(int arg1, int arg2, int arg3) { ... } 初始化它 这很简单。 但我想要实现的是,论点需要改变。 例如,如果将1 传递给arg1,则第二个和第三个参数不采用 Int,而是采用 float。

这可以在 C# .NET Core 中实现吗? 如果不是,那在 C# 中是否有可能? 怎么做?

【问题讨论】:

  • 听起来您要问的是构造函数重载。您可以在对象上创建任意数量的不同构造函数。
  • 这听起来很奇怪——为什么需要使类型依赖于第一个参数?为什么不直接创建不同的重载(并跳过第一个参数)?
  • 不,这是不可能的。您可能想描述您想要实现的目标,我们或许可以通过其他方法为您提供帮助。
  • @David 我该怎么做?比如,基本语法是什么?
  • 您所描述的内容需要 C# 不支持的依赖类型。你有一个为什么需要这样做的例子吗?

标签: c# class oop


【解决方案1】:

你可以重载你的构造函数

public Class1(int arg1, float arg3)

【讨论】:

  • 如果你这样做,消费者可以决定他们使用哪个重载,而不管arg1的值。
【解决方案2】:

你为什么不像这样创建两个不同的重载构造函数:

public Class1(int arg1, int arg2, int arg3) {
     if(arg1 == 1) {
         throw new InvalidOperationException("Wrong constructor");
     }
     ...
}

public Class1(int arg1, float arg2, float arg3) {
     if(arg1 != 1) {
         throw new InvalidOperationException("Wrong constructor");
     }
     ...
}

或者,如果你喜欢它更容易一点,没有例外(这将是我的首选方式):

public Class1(int arg1, float _arg2, float _arg3) {
     if(arg1 != 1) { // Your int constructor, use arg2 and arg3 vars declared below
         int arg2 = (int) _arg2;
         int arg3 = (int) _arg3;
         ...
     } else {
         // Your float constructor, use the _arg2 and _arg3 as your floats
         ...
     }
}

您在运行时更改变量的预期解决方案是不可能的,但我认为我发布的最后一个代码非常接近。

【讨论】:

  • 解释清楚,谢谢!做到了。但是浮动的东西只是一个例子。我正在接受字符串或整数。但第一个选项正是我想要的。
【解决方案3】:

所以我确实找到了另一个答案。

您可以只创建一个带有所有参数的构造函数,然后允许它们为空,然后检查哪些为空,哪些已设置。

可能不是最好的方法,但它有效......不会使用它,但只是想到它......

【讨论】:

    猜你喜欢
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2021-05-17
    • 2013-05-04
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多