在使用Linq to Sql时,我创建了一个将数据传送到网页的独立类。为了简化创建这些渡口对象,我使用专门的构造函数或显式转换运算符。我有两个问题。构造函数或显式类型转换
首先从可读性的角度来看哪种方法更好?
二而产生的CLR代码看起来是一样的我,是其中一个会被编译器处理比其他的不同(拉姆达的或如)存在的情况。
示例代码(DatabaseFoo使用专门的构造和BusinessFoo使用显式运算符):
public class DatabaseFoo
{
private static int idCounter; // just to help with generating data
public int Id { get; set; }
public string Name { get; set; }
public DatabaseFoo()
{
Id = idCounter++;
Name = string.Format("Test{0}", Id);
}
public DatabaseFoo(BusinessFoo foo)
{
this.Id = foo.Id;
this.Name = foo.Name;
}
}
public class BusinessFoo
{
public int Id { get; set; }
public string Name { get; set; }
public static explicit operator BusinessFoo(DatabaseFoo foo)
{
return FromDatabaseFoo(foo);
}
public static BusinessFoo FromDatabaseFoo(DatabaseFoo foo)
{
return new BusinessFoo {Id = foo.Id, Name = foo.Name};
}
}
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Creating the initial list of DatabaseFoo");
IEnumerable<DatabaseFoo> dafoos = new List<DatabaseFoo>() { new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo(), new DatabaseFoo()};
foreach(DatabaseFoo dafoo in dafoos)
Console.WriteLine(string.Format("{0}\t{1}", dafoo.Id, dafoo.Name));
Console.WriteLine("Casting the list of DatabaseFoo to a list of BusinessFoo");
IEnumerable<BusinessFoo> bufoos = from x in dafoos
select (BusinessFoo) x;
foreach (BusinessFoo bufoo in bufoos)
Console.WriteLine(string.Format("{0}\t{1}", bufoo.Id, bufoo.Name));
Console.WriteLine("Creating a new list of DatabaseFoo by calling the constructor taking BusinessFoo");
IEnumerable<DatabaseFoo> fufoos = from x in bufoos
select new DatabaseFoo(x);
foreach(DatabaseFoo fufoo in fufoos)
Console.WriteLine(string.Format("{0}\t{1}", fufoo.Id, fufoo.Name));
}
}
我可能会在DatabaseFoo类中使用静态ToBusinessFoo和静态FromBusinessFoo,并避免将任何内容放入BusinessFoo中,因为重点在于尽量减少BusinessFoo对数据的了解。 转换也不适合我。所以你更喜欢静态方法来使用一个构造函数:DatabaseFoo(businessFoo)? – Felan 2010-04-10 19:42:41
@Felan:你可以在DatabaseFoo上将它设置为一个*扩展*方法......这样DatabaseFoo本身不知道它,但它看起来像它。说实话,构造函数或静态方法不会让我感到困扰。静态方法有一些优点,比如能够缓存或返回null,并且有名称来消除参数的歧义。建设者更典型。 – 2010-04-10 21:27:08