构造函数或显式强制转换

时间:2010-04-10 17:51:23

标签: c# linq linq-to-sql

在使用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));
    }
}

2 个答案:

答案 0 :(得分:6)

我在大多数情况下都不是转换的忠实粉丝 - 无论是明示还是暗示。相同的语法:(TypeName) expression用于各种不同类型的转换,并且知道编译器正在应用哪种类型会让人感到有点困惑。

FromDatabaseFoo这样的静态工厂方法很不错 - 您可能还想在ToBusinessFoo上使用DatabaseFoo的实例方法。在我看来,这两者都比用户定义的转换更清晰。

(这并不是说自定义转换总是一个坏主意,请注意。我一般都对它们保持警惕。)

答案 1 :(得分:2)

我建议您查看AutoMapper。它将使您的代码更加清晰,并将这些对象之间的映射分开,这将使它们独立且更可重用。