重载构造函数和方法似乎很混乱,即简单地通过参数的顺序和数量来区分它们.是不是有办法,也许用泛型,干净利落地这样做,即使你只有一个参数(例如字符串idCode /字符串状态),你仍然可以区分它们?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TheForm tf1 = new TheForm("online", DateTime.Now);
TheForm tf2 = new TheForm(DateTime.Now, "form1");
}
}
public class TheForm
{
public TheForm(string status, DateTime startTime)
{
//...
}
public TheForm(DateTime startTime, string idCode)
{
//...
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以考虑为该课程设置一个Fluent Builder,尽管它更有用.这将允许你写这样的东西:
var form = new TheFormBuilder().WithStatus("foo").WithStartTime(dt).Build();
Run Code Online (Sandbox Code Playgroud)
它更明确,但不是更好.这绝对是更多的工作.
在C#4中,您可以选择在调用构造函数时编写参数名称:
var form = new TheForm(status: "Foo", startTime: dt);
Run Code Online (Sandbox Code Playgroud)
.NET 3.0的新对象初始化功能比重载的构造函数更灵活.这是一个简单的例子:
public class Item
{
public string Name {get; set;}
public int Index {get; set;}
public string Caption {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
正如现在所写,我们可以在代码中执行以下操作:
var x = new item {Name=”FooBar”};
var x = new item {Name=”FooBar”, Index=”1”, Caption=”Foo Bar”};
Run Code Online (Sandbox Code Playgroud)
如果我想在属性初始化期间添加功能,我只会向类Item添加重载的构造函数.例如:
public class Item
{
public Item() {}
public Item(string name)
{
Name = name;
Caption = name; //defaulting name to caption
}
public Item(string name, int index) : this(name)
{
Index = index;
}
public Item(string name, int index, string caption) : this(name, int)
{
Caption = caption;
}
public string Name {get; set;}
public int Index {get; set;}
public string Caption {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
注意:如果这是一个子类,我可以使用"base"关键字链接到父构造函数.
如果我正在编写一个"配置"类的类,我使用Fluent方法代替重载的构造函数.
例如,如果我将这些方法添加到Item类:
public Item WithName(string name)
{
Name = name;
return this;
}
public Item WithIndex(int index)
{
Index = index;
return this;
}
public Item WithCaption(string caption)
{
Caption = caption;
return this;
}
Run Code Online (Sandbox Code Playgroud)
我可以写这样的代码:
var x = new Item().WithName(“FooBar”).WithIndex(“99”).WithCaption(“Foo Bar”);
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是将结构与给定类型的单个参数区分开来,就是在类型本身或工厂类中使用非实例工厂方法.
例如(在类型本身上)
(另)
public class TheForm
{
public static TheForm CreateWithId(string idCode)
{
}
public static TheForm CreateWithStatus(string status)
{
}
}
Run Code Online (Sandbox Code Playgroud)