隐式运算符,linq和lambda表达式可以使代码不那么可读.但是什么更可读?[英] Implicit operators, Linq and Lambda expressions can make code less readable. But what is more readable?

本文是小编为大家收集整理的关于隐式运算符,linq和lambda表达式可以使代码不那么可读.但是什么更可读?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

回答这个问题 为什么linq为什么会当我定义隐式铸件时,Cast 操作失败了?

我发现有多种隐式施放对象之间的方法.

考虑以下两个类:

public class Class1 
{ 
    public int Test1;
}
public class Class2
{
    public int Test2;
    public static implicit operator Class1(Class2 item)
    {
        return new Class1 { Test1 = item.Test2 };
    }
}

为了将列表转换为列表,我们可以执行以下任何操作:

List<Class2> items = new List<Class2> { new Class2 { Test2 = 9 } };

foreach (Class1 item in items)
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.ConvertAll<Class1>(i=>i))
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.Select<Class2, Class1>(i=> i))
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.Select(i=>i))
{
    Console.WriteLine(item.Test1);
}

但是,哪个更清楚地阅读和理解发生了什么?

推荐答案

第一个自然.隐式演员的全部要点是,两种类型足够相似,以至于概念上的意义仅仅是因为它们是相同的.

你会拒绝吗?

List<byte> items = new List<byte> { 1, 2, 3, 4 };

foreach (int i in items) // since bytes implictly cast to ints
{
    Console.WriteLine(i + 1000);
}

如果您还可以,但是您不喜欢上面问题中的第一个配方,那么我认为您应该使用明确的演员.

本文地址:https://www.itbaoku.cn/post/1557210.html

问题描述

In answering this question Why does a Linq Cast<T> operation fail when I have an implicit cast defined?

I have found that there are a number of ways to implicitly cast between objects.

Consider the following two classes:

public class Class1 
{ 
    public int Test1;
}
public class Class2
{
    public int Test2;
    public static implicit operator Class1(Class2 item)
    {
        return new Class1 { Test1 = item.Test2 };
    }
}

In order to convert a List to List we can do any of the following:

List<Class2> items = new List<Class2> { new Class2 { Test2 = 9 } };

foreach (Class1 item in items)
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.ConvertAll<Class1>(i=>i))
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.Select<Class2, Class1>(i=> i))
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.Select(i=>i))
{
    Console.WriteLine(item.Test1);
}

But which is clearer to read and understand what is going on?

推荐答案

The first, naturally. The whole point of an implicit cast is that the two types are sufficiently similar that it makes conceptual sense to just figure that they are the same.

Would you balk at this?

List<byte> items = new List<byte> { 1, 2, 3, 4 };

foreach (int i in items) // since bytes implictly cast to ints
{
    Console.WriteLine(i + 1000);
}

If that's OK with you, but you don't like your first formulation in the question above, then I think you should use an explicit cast instead.