在使用 Linq to Sql 时,我创建了一个单独的类来将数据传送到网页。为了简化创建这些渡轮对象,我使用专门的构造函数或显式转换运算符。我有两个问题。
首先,从可读性的角度来看,哪种方法更好?
其次,虽然生成的 clr 代码对我来说似乎是相同的,但在某些情况下,编译器(在 lambda 等中)会将一个代码视为不同于另一个代码。
示例代码(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));
}
}
最佳答案
在大多数情况下,我不太喜欢转换 - 无论是显式还是隐式。相同的语法:(TypeName) expression
用于各种不同类型的转换,要知道编译器正在应用哪种类型可能会让人有些困惑。
FromDatabaseFoo
之类的静态工厂方法很好 - 您可能还希望在 DatabaseFoo
上拥有 ToBusinessFoo
的实例方法。在我看来,这两者都比用户定义的转化更清晰。
(请注意,这并不是说自定义转换总是是个坏主意。我只是总体上对它们保持警惕。)
关于c# - 构造函数或显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614300/