根据参数值重载方法?
我有一个类,我希望类构造函数根据第一个参数的值而变化。
public class Calc
{
public Calc( Operator calcOpr = Operator.Concat, string sourceName, string newString )
{
calcOperator = calcOpr;
sourceType = dataType;
}
public Calc( Operator calcOpr = Operator.PadLeft, int startindex, int count )
{
calcOperator = calcOpr;
sourceType = dataType;
}
现在我知道上面的代码不是有效的代码,但作为伪代码,它确实显示了我想要实现的目标。
有没有某种方法可以根据参数值重载类构造函数?
编辑:我想这样做,以便实例化类时所需的参数根据不同的 Operator
值进行更改。
I have a class and I want the class constructor to vary according to the value of the first parameter.
public class Calc
{
public Calc( Operator calcOpr = Operator.Concat, string sourceName, string newString )
{
calcOperator = calcOpr;
sourceType = dataType;
}
public Calc( Operator calcOpr = Operator.PadLeft, int startindex, int count )
{
calcOperator = calcOpr;
sourceType = dataType;
}
Now I KNOW the above is not valid code, but as pseudocode it does show what I want to achieve.
Is there some way of getting class constructors overloaded based on the parameter values?
EDIT: I want to do this so that that the parameters required when instantiating the class are changed according to different Operator
values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以这样实现它:
You could implement it that way:
我认为这里使用的一个好的模式是工厂。
CalcFactory
允许调用者明确了解Calc
的具体目标。该工厂可以在内部使用@Roflcoptr的构造函数。
I think that a good pattern to use here would be a factory.
A
CalcFactory
would allow callers to know explicitly the concrete objective of theCalc
.This factory could use @Roflcoptr's constructors internally.
示例代码有点偏离,因为它们都有不同的签名(第二个参数是 string 与 int)。因此传递 int 或 string 就已经选择了正确的重载。
当您想要具有相同方法签名的不同行为时,只需打开枚举:
编辑(到您的编辑)
方法具有固定签名,因此如果您希望有 1 个构造函数来创建基于运算符的正确类型,您不必在其中传递所有可能的参数。 (错误代码):
闻起来不好。
我想我会选择单独的方法而不是构造函数重载。 (静态,因此您可以从类型中调用它们)
此外,您可能希望考虑为 Concat 和 PadLeft 创建派生类,这些类派生自 Calc 和重载方法/添加特定属性。事实上,我认为这就是我会做的,但你必须详细说明你正在做什么。
The example code is a bit off, since they both have a different signature (string vs int for the second argument). So passing and int or string would already select the right overload.
When you want different behaviour with the same method signature, just switch on the enum:
Edit (to your edit)
A method has a fixed signature, so if you'd want to have 1 constructor that creates the right type based on the Operator, you'd have t pass all possible arguments in there. (bad code) :
Doesn't smell good.
I think I would go for separate method instead of constructor overloads. (Static so you can call them from the type)
Also you may want to look into creating derived classes for Concat and PadLeft that derive from Calc and overload methods/ add specific properties. Actually I think that's what I would do but you'd have to tell a bit more about what you're doing exactly.
也许您可以尝试使用可变参数的构造函数。
May be You can try a constrcutor with variable arguments.