隐式运算符,Linq和Lambda表达式会使代码的可读性降低.但是,更具可读性的是什么?
在回答这个问题时 为什么要使用Linq Cast< T>我定义了隐式强制转换时操作失败?
我发现有很多方法可以在对象之间隐式转换.
I have found that there are a number of ways to implicitly cast between objects.
请考虑以下两个类:
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.
你会为此讨厌吗?
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.