仅用几个不同的参数减少非常长的构造函数重载的数量 [英] Reducing number of very long constructor overloads with just a few different parameters

查看:46
本文介绍了仅用几个不同的参数减少非常长的构造函数重载的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个自定义界面系统,该系统使用基本的UI控件(如按钮,标签等).某些控件具有许多选项,因此它们使用长构造函数,并且它们之间只有一个或两个参数不同.这是正在进行的工作,因此我大量更改了可选参数,并且需要相当长的时间才能将更改应用于所有构造函数.

I made custom interface system which uses basic UI controls like button, label, etc. Some controls have many options, so they use long constructors, and they only differ in one or two parameters. And this is work in progress, so I change optional parameters a lot, and it takes quite some time to apply changes to all constructors.

public Button(string Text, Rectangle Rect, Texture2D Texture, bool moreStuff)
public Button(string Text, Point Position, Texture2D Texture, bool moreStuff)
public Button(string Text, Vector2 Position, Texture2D Texture, bool moreStuff)

我尝试使用 dynamic 关键字代替 Rectangle Point Vector2 来减少构造函数的数量,并且它可以编译,运行,并且目前看来还可以.但是也许我错过了一些可能会在以后打破这种方法的东西?

I tried using dynamic keyword instead of Rectangle, Point and Vector2 to decrease the number of constructors, and it compiles, works, and seems ok for the moment. But maybe I'm missing something that might break this approach later?

要找出传递为 dynamic Position 的内容,请检查 .GetType().Name ,使用开关并在 default处引发异常:,如果它不是可识别的类型.

To find out what was passed as dynamic Position I check for .GetType().Name, use a switch and throw an exception at default: if it wasn't a recognized type.

这样做是不是很好,还是有更好(更安全或更合适)的方法?

Is it fine to do it like this, or is there a better (more safe or appropriate) way?

当前可以创建内联的 Button 的完全自定义实例,而我不想失去这种能力.

Currently it's possible to create a fully customized instance of Button inline, and I wouldn't like to lose that ability.

推荐答案

如果发现乏味,则无需定义构造函数参数.您可以很好地使用对象初始化程序:

You don't need to define constructor arguments if you're finding it tedious. You could use an object initializer quite nicely:

SomeButton button = new SomeButton()
{
    Text = "",
    MoreStuff = false
};

这篇关于仅用几个不同的参数减少非常长的构造函数重载的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆