在使用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