c# - 构造函数或显式转换

标签 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));
    }
}

最佳答案

在大多数情况下,我不太喜欢转换 - 无论是显式还是隐式。相同的语法:(TypeName) expression 用于各种不同类型的转换,要知道编译器正在应用哪种类型可能会让人有些困惑。

FromDatabaseFoo 之类的静态工厂方法很好 - 您可能还希望在 DatabaseFoo 上拥有 ToBusinessFoo 的实例方法。在我看来,这两者都比用户定义的转化更清晰。

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

关于c# - 构造函数或显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614300/

相关文章:

c# - WPF MVVM 文本框验证

c# - 如果条件为假,则 Razor 添加类

linq - 如何将LINQ表达式组合为一个?

c# - 为什么我应该在 LINQ to SQL 中使用 IQueryable<T> 而不是 List<T>

c# - 如何在 C# 中使用 Web HDFS REST API 附加文件?

c# - 从字符串构建 Linq 排序表达式结果为 'Expression of "system.int3 2"can not be used for return type "System.Object"'

C# linq 更改构造函数无法添加新值

c# - 将大量整数加入 LINQ 查询

c# - LINQ:如何在 linq 中动态使用 ORDER BY 但前提是变量不是 string.empty 或 null

c# - 当字符串为数字时,如何在计算值的同时按字母顺序对字符串进行排序?