隐式运算符、Linq 和 Lambda 表达式可能会降低代码的可读性。 但什么更具可读性呢?
在回答这个问题时 为什么 Linq演员
我发现有多种方法可以在对象之间进行隐式转换。
考虑以下两个类:
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 转换为 List,我们可以执行以下任一操作:
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);
}
但是哪个更容易阅读和理解正在发生的事情?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个,自然是。 隐式转换的要点在于,这两种类型非常相似,因此认为它们相同是有概念意义的。
你会对此犹豫吗?
如果您同意,但您不喜欢上面问题中的第一个表述,那么我认为您应该使用显式强制转换。
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?
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.